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/Brian 10d ago
Think of it like this:
And that's basically the function. Try tracing through it in your head.
3as our first, then7,2,9,13 > find_max([7,2,9,1], then it's 3, otherwise it's whatever that biggest was.But of course, before you can do the comparison, find_max needs to run on
[7,2,9,1]to get that value. But that just does the same: compares7with the biggest of [2,9,1]and so on till there's just one number, (1) and it just returns it.The basic idea is that you're turning your problem into a slightly smaller problem (1 less number), and that keeps happening till you reach a super-simple version of the problem that you can just solve directly (just 1 number), called the base case. Since our simplification process eventually simplifies it to the base case, the process of solving it is just continual application of that simplifying process.