Jan-23-2022, 07:15 PM
(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.
(Jan-23-2022, 04:53 PM)vlearner Wrote: I checked this solution but I am not getting how the code works. can anyone explain the logic of code?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.
![Smile Smile](https://python-forum.io/images/smilies/smile.png)
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