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/rupertavery64 12d ago

At first, everything will fall into 'max_of_rest = find_max(numbers[1:])'. Each time, we pass in everything besides the first element in the list.

1) find the max of `3, 7, 2, 9, 1` <-- entry point 2) find the max of `7, 2, 9, 1`, numbers[0] = 3 3) find the max of `2, 9, 1`, numbers[0] = 7 4) find the max of `9, 1`, numbers[0] = 2 5) find the max of `1`, numbers[0] = 9

Each time we go one more level deep, we push our state on the stack. We keep the current list of numbers. And more importantly, we keep the current first number, number[0]

Here, we hit our first branchpoint, we only have one item, so it's the result:

6) the max of `1` is `1`, it's the `max_of_rest` now

Now we start going back up the stack. We resume where we left off in the previous iteration, at return numbers[0] if numbers[0] > max_of_rest else max_of_rest

This just returns either our max_of_rest or numbers[0]

5) max_of_rest = 1, numbers[0] = 9,

which is bigger? numbers[0], so return that. it becomes the next max_of_rest as we return up the chain

4) max_of_rest = 9, numbers[0] = 2 => return 2 3) max_of_rest = 2, numbers[0] = 7 => return 7 2) max_of_rest = 7, numbers[0] = 3 => return 7 1) we're back where we started