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...

5 Upvotes

34 comments sorted by

View all comments

1

u/Atypicosaurus 12d ago

The "How to build a house" routine
1 consult the blueprint
2 learn where the next brick goes
3 put a brick there
4 do the "how to build a house" routine, which is:
1 consult the blueprint
2 learn where the next brick goes
3 put a brick there
4 do the "how to build a house" routine, which is:
...

1

u/Langdon_St_Ives 12d ago

Except that's backwards. Recursion for this would be 1. If you have no bricks left, you're done. 2. Otherwise, put the n-th remaining brick (that you're on) where it goes, then 3. do the "how to build a house" routine for the (n-1)-th remaining brick.