Jan-23-2022, 07:20 PM
(Jan-23-2022, 07:15 PM)menator01 Wrote:(Jan-23-2022, 06:57 PM)ibreeden Wrote: Haha @menator01 , you are cheating!It would work fine if the list would remain limited to two dimensions, but it it is't. Vlearner had a list with a deeper nesting level:
[[4,5],[7,8,[20]],100]
. When you run your code on this list you get:
@vlearner : your code is almost correct, you must change line 13 to
Error:Traceback (most recent call last): File "/home/ibreeden/PycharmProjects/Forum/forum02.py", line 43, in <module> print(sum_nested_list(mylist)) File "/home/ibreeden/PycharmProjects/Forum/forum02.py", line 33, in sum_nested_list total = total + sum(num) TypeError: unsupported operand type(s) for +: 'int' and 'list'
total += sum_nested_list(l[j])... or else you lose the result of your recursive call.
The algorithm is straigtforward. If you would pass a list with integers to your function, it would return the sum of the numbers. But if one of the elements of the list is again a (nested) list, then this list is handled by the (recursive) call to the same function. In that case the returned sum must be added to the total.
You are correct.
This seems to work
mylist = [5,[5, [9,3], 3],10,8,5,[10, [5, [5,2]], 8]] # List of numbers def sum_nested_list(mylist): # set the finction variable total = 0 # Loop through the list checking for other list for num in mylist: if type(num) == list: # If a list is found, get the sum and add to total total += sum_nested_list(num) else: total += num # else add the num to total return total # return the total print(f'Final total is {sum_nested_list(mylist)}')
Output:Final total is 78
I welcome all feedback.
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags