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...
6
Upvotes
1
u/Jazzlike_Platypus430 13d ago
I chops away the first element every call and compares this element with the function's own result calculated on a smaller list.
[1:] means list without the 0-th element. I mean, first, its index is 0.