COSC 2306: Data Programming - Recursive Function Call Stack Visualizer
Comma separated list of numbers.
A recursive function can operate on lists by slowly shrinking the list on each step until it reaches a base case:
len(l) == 1). The largest element in a single-element list is simply the element itself!l[1:]). Find the largest of the rest, then compare it with the first element (l[0]).Notice how the function "winds" up the stack finding smaller and smaller slices until one element is left, then "unwinds" by making comparisons on the way back down!
def largest(l):
if len(l) == 1:
return l[0]
else:
max = largest(l[1:])
if l[0] >= max:
return l[0]
else:
return max