def sum_list(L: list) -> float: """ Return sum of the numbers in L.
L --- a possibly nested list of numbers. L, and all sublists, are non-empty
>>> sum_list([1, 2, 3]) 6 >>> sum_list([1, [2, 3, [4]], 5]) 15 """
return sum([sum_list(x) if isinstance(x, list) else x for x in L])
L --- a possibly nested list of numbers. L, and all sublists, are non-empty
>>> sum_list([1, 2, 3]) 6 >>> sum_list([1, [2, 3, [4]], 5]) 15 """
return sum([sum_list(x) if isinstance(x, list) else x for x in L])
and this code for the same function:
def sum_list(L: list) -> float:
total = 0
for x in L:
if isinstance(x,list):
total = sum([total, sum_list(x)])
else:
total = sum([total,x])
return total
The seemingly complicated problem of how to solve a list of lists is easily solved with recursion.
To sum a list of lists, start with the initial list, if the first index of that list is a number, at it to the sum, if the next object at the next index is also a number, at it to the sum too, and so on. It is easy to write a function to do this, it's just getting the sum of numbers in a list. When a nested list is encountered, we still want to get the sum of the numbers in a list, however our object is a list instead of a digit. So, we just call our function on this list, then we get the sum of the nested list and it is added to our total sum. The big problem is solved by repeating the solution to a sub problem, in this case, summing lists.
The recursion handout, which is from the lecture, and the lab about recursion helped me out. Especially during the lab, the lab worksheet contains the way to tracing each steps of recursion function, so that I was able to understand step by step. Not only from the lecture and lab, but also from piazza, I learned some confusing concepts. For example, I was confused about writing each steps of inner recursive part, but viewing other classmates' comments and posts, I solved my difficulties.