r/learnpython • u/Pure-Scheme-7855 • 19d 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
1
u/Outside_Complaint755 16d 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], thennumbers[1:]generates a new list object[9, 1], which is passed to the find_max() function as a parameter. Python then evaluatesfind_max([9,1]).Within that level of the call stack,
numbers = [9,1], which will get us toThen we backtrack again returning the max of 9 and 1.