This week we learned how to define functions that can call themselves over again and again. For example, lets create a function that takes the sum of a list of numbers. Normally, using an accumulator I would do something like this:
def sum_list(L: list) -> float:
""" Return the sum of the numbers in list L
"""
sums = 0
for x in L:
sums += x
return sums
What if we have nested lists inside other lists? Such as, L = [2, 3, [1, 5]] My original code will return a type error:
unsupported operand type(s) for +=: 'int' and 'list'
Obviously we can't add ints with lists... there must be another way.
def sum_list(L: list) -> float:
""" Return the sum of the numbers in list L
"""
return sum([sum_list(x) if isinstance(x, list) else x for x in L])
Let's take this step by step:
1. It checks if the first value of L is a list.
a) if it is a list, it loops over each value in that list and takes the sum of their values.
b) if it is a list and has another list inside it, it loops over the values in the inner list first. It takes the sums on the inside before it moves on to the next value in the outer list.
c) if it is not a list, it moves on to the next value in L.
2. Lastly, using the built-in: sum(), this takes the sum of the linear list.