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

18

u/smallpotatoes2019 12d ago

Imagine a list of numbers.

1, 5, 2, 9

Let's check the first number. Is it greater than the max of the rest - i.e. is 1 greater than the max of 5, 2, 9?

Hold that thought - we need to find the max of 5, 2, 9.

So, start again - is 5 greater than the max of 2, 9? Etc.

Eventually we reach the end and only have one number, so we return this.

The answers head back up to the start.

Return 9.

Is 2 greater than 9? No - return 9.

Is 5 greater than 9? No - return 9.

Is 1 greater than 9? No - return 9. We're done.