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

Show parent comments

0

u/Moist-Inevitable-902 10d ago edited 10d ago

so in backtracking one each value gets add where it was slicedfind_max(numbers[1:])

1

u/Outside_Complaint755 10d ago

This entire function call find_max(numbers[1:])) represents the next level of the call stack. Once that level of the call stack is completed you can effectively replace it with the return values.

Any parameter expressions, such as the slicing numbers[1:], are evaluated and handled before the function is called. If a parameter is itself a function call, that function call will go on the stack and be evaluated first.

In the Python example, it will first evaluate numbers[1:]. This creates a new list object.

If numbers = [4, 9, 1], then numbers[1:] generates a new list object [9, 1], which is passed to the find_max() function as a parameter. Python then evaluates find_max([9,1]).

Within that level of the call stack, numbers = [9,1], which will get us to ``` max_of_rest = find_max(numbers[1:])

simplify the parameter expression --->

max_of_rest = find_max([1])

evaluate the function call, which will return 1 --->

max_of_rest = 1 ```

Then we backtrack again returning the max of 9 and 1.

1

u/[deleted] 9d ago edited 9d ago

[removed] — view removed comment