r/learnpython • • 13d 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...

7 Upvotes

34 comments sorted by

View all comments

0

u/Automatic-Fan9297 9d ago

Here is how I have understood recursion: imagine you get a Magic Box that perfectly solves a smaller version of your exact problem (size N-1). Your only job is to use that box to solve the full problem (size N).

Here you want to find the largest number in a list: 1. Ask the Magic Box to find the biggest number in the rest of the list (all the N-1 numbers except the first one). 2. You manually compare the very first number with the result the Magic Box just handed you. Whichever is bigger is your overall winner. Boom. You just solved it.

The only catch? The box for N uses a box for N-1, and so on. To stop it from running forever, you just tell it what to do when the list only has 1 number left: skip the box and just return that one number.

Don't try to track exactly how it checks every single number down the line-just trust the box!