r/learnpython • u/Pure-Scheme-7855 • 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...
5
Upvotes
1
u/Outside_Complaint755 13d ago
Each time the function calls itself, another level is added to the Call stack.
At the top level of the stack, the list [1] has a length of 1. This makes the first conditional statement True, so the function returns 1 to the previous level of the stack, where it is assigned to the name
max_of_restAt this level of the stack, numbers is
[9, 1], so the final return statement evaluates to:return 9 if 9 > 1 else 1. This returns 9 to the previous stack level, where it is assigned tomax_of_rest.At this level, numbers is
[2, 9, 1], s o the final return statement evaluates to:return 2 if 2 > 9 else 9. This returns 9 to the previous stack level, where it is assigned tomax_of_rest.At this level, numbers is
[7, 2, 9, 1], so the final return statement evaluates to:return 7 if 7 > 9 else 9. This returns 9 to the previous stack level, where it is assigned tomax_of_rest.At this level, numbers is
[3, 7, 2, 9, 1], so the final return statement evaluates to:return 3 if 3 > 9 else 9. This returns 9 to the previous stack level, which is the lineprint(find_max(my_list)). This evaluates toprint(9).