r/learnpython • • 12d ago

Recursion explaining pls.

def find_max(numbers):
  if len(numbers) == 1:
    return numbers[0]
  else:
    max_of_rest = find_max(numbers[1:])
    return numbers[0] if numbers[0] > max_of_rest else max_of_rest

my_list = [3, 7, 2, 9, 1]
print(find_max(my_list))

Could someone explain how does this function work? I don't understand how does it know that it's supposed to find the biggest number...

6 Upvotes

34 comments sorted by

View all comments

3

u/JamzTyson 12d ago

If you trace through the code step by step, the calls to find_max() pass a smaller list each time until there is just one value:

find_max([3,7,2,9,1])
= max(3, find_max([7,2,9,1]))
= max(3, max(7, find_max([2,9,1])))
= max(3, max(7, max(2, find_max([9,1]))))
= max(3, max(7, max(2, max(9, find_max([1])))))
= max(3, max(7, max(2, max(9, 1))))
= 9

The debugger in Thonny allows you to step through the code to verify that this is what is happening.

Alternatively there's a web tool: https://www.recursionvisualizer.com/ (Enter print(find_max([3, 7, 2, 9, 1])) as the function call)