Python Forum
Python Program to Find the Total Sum of a Nested List
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Python Program to Find the Total Sum of a Nested List
#1
kindly guide me how should I proceed to solve this problem:
[[4,5],[7,8,[20]],100]
Reply
#2
What have you tried? Hint: recursion is useful for problems like this.
Reply
#3
(Jan-23-2022, 04:25 PM)ndc85430 Wrote: What have you tried? Hint: recursion is useful for problems like this.

def sum_nestedlist( l ):
   
    # specify that global variable is
    # referred to here in this function
    total = 0
     
    for j in range(len(l)):
       
        if type(l[j]) == list :
           
            # call the same function if
            # the element is a list
            sum_nestedlist(l[j])
        else:
           
            # if it's a single element
            # and not a list, add it to total
            total += l[j]  
             
    return total
             
print(sum_nestedlist([[1,2,3],[4,[5,6]],7]))
I checked this solution but I am not getting how the code works. can anyone explain the logic of code?
Reply
#4
I don't know that i would use range on the list.
All though there are other ways but, maybe like this

mylist = [5,[5, 3, 3],5,5,5] # 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(num)
        else:
            total += num # else add the num to total
    return total # return the total

print(sum_nested_list(mylist))
Output:
31
I welcome all feedback.
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags


Reply
#5
You wrote code you don't understand?
Reply
#6
Haha @menator01 , you are cheating! Smile 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:
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'
@vlearner : your code is almost correct, you must change line 13 to
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.
Reply
#7
Python 🦄🥴❓
def flatten(seq):
    for item in seq:
        match item:
            case list():
                yield from flatten(item)
            case _:
                yield item

lst = [[1,2,3],[4,[5,6]],7]
print(sum(flatten(lst)))
Output:
28
menator01 likes this post
Reply
#8
(Jan-23-2022, 06:57 PM)ibreeden Wrote: Haha @menator01 , you are cheating! Smile 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:
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'
@vlearner : your code is almost correct, you must change line 13 to
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
I welcome all feedback.
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags


Reply
#9
(Jan-23-2022, 07:15 PM)menator01 Wrote:
(Jan-23-2022, 06:57 PM)ibreeden Wrote: Haha @menator01 , you are cheating! Smile 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:
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'
@vlearner : your code is almost correct, you must change line 13 to
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. Smile

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
ibreeden likes this post
I welcome all feedback.
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags


Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Program to find Mode of a list PythonBoy 6 999 Sep-12-2023, 09:31 AM
Last Post: PythonBoy
  find random numbers that are = to the first 2 number of a list. Frankduc 23 3,014 Apr-05-2023, 07:36 PM
Last Post: Frankduc
  List all possibilities of a nested-list by flattened lists sparkt 1 878 Feb-23-2023, 02:21 PM
Last Post: sparkt
  Find (each) element from a list in a file tester_V 3 1,156 Nov-15-2022, 08:40 PM
Last Post: tester_V
  read a text file, find all integers, append to list oldtrafford 12 3,372 Aug-11-2022, 08:23 AM
Last Post: Pedroski55
  find some word in text list file and a bit change to them RolanRoll 3 1,482 Jun-27-2022, 01:36 AM
Last Post: RolanRoll
  How to find the second lowest element in the list? Anonymous 3 1,905 May-31-2022, 01:58 PM
Last Post: Larz60+
  Updating nested dict list keys tbaror 2 1,243 Feb-09-2022, 09:37 AM
Last Post: tbaror
  Find the highest value of a list Menthix 4 1,835 Oct-29-2021, 02:32 PM
Last Post: Menthix
  Looping through nested elements and updating the original list Alex_James 3 2,070 Aug-19-2021, 12:05 PM
Last Post: Alex_James

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020