Recursion
Many functions act on list objects to produce values asuch as the max value, sum of all values, etc. However when the list has a list within it, functions like sum must be called on the inner list to produce a value computable along with the other values. For example, sum([5, [2, 3], 5]) would result in an error due to the addition of an int and list. what would need to first happen is that sum([2, 3]) is first computed, then sum([5, sum([2, 3]), 5]). We can utilize a for loop in order to cycle through every object in the lowest depth list. If the current object is not a list, return/ process accordingly. However if the current object is a list, run the same for loop on the inner list.
def summer(L):
if isinstance(list, L):
return sum([summer(x) for x in L])
else:
return L
On the list [5, [2, 3], 5], the objects of the outer list 5, [2, 3], and 5 will be run through the function. the 5 and 5 are not lists, and will be returned into the outer list, and the [2, 3] will be acted on by summer (summer([2, 3])). On a list with a depth of one the function will simply sum the values as all objects are returned in a list, and are summed. Thus summer([2, 3]) -> sum([summer(2), summer(3)]) -> sum([2, 3]) -> 5. This value is then returned into the outer list. sum(summer(x) for x in [5, [2, 3], 5]) -> sum([summer(5), summer([2, 3]), summer(5)]) -> sum([5, 5, 5]) -> 15. As lists gain a larger depth, the summer function is called more times as it iterates over every internal list.
No comments:
Post a Comment