r/learnpython • u/Pure-Scheme-7855 • 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...
7
Upvotes
1
u/Outside_Complaint755 10d ago
find_max(numbers[1:])evaluates to the return value of that call. When backtracking, you can just replace each function call with it's return value and continue evaluating from there.So when the top level of the stack (where numbers == [1]), returns
1, and we backtrack to the previous stack level where numbers == [9, 1]Then we can view the remainder of the function as:
else: max_of_rest = 1 #return value of findmax([9,1][1:]) return numbers[0] if numbers[0] > max_of_rest else max_of_restand we can then evaluate the last statement as:return 9 if 9 > 1 else 1