BugLab012 / 020up to 100
recursioncontrol-flowfunctionsmedium

The Lost Return

The function find_max(lst) should recursively find and return the maximum value in a non-empty list.

When the largest element happens to be at index 0, it works. For any other list — where the maximum is somewhere in the middle or at the end — it returns None.

The recursive logic is correct. The base case is correct. There is exactly one line missing.

# your fix
+ must use recursion
hint 2after hint 1
hint 3after hint 2
solution

Read the code. Before running anything: what does the last line below give?

def find_max(lst):
"""
Recursively finds and returns the maximum value in a non-empty list.
Example: find_max([3, 1, 4, 1, 5, 9]) -> 9
"""
if len(lst) == 1:
return lst[0]
rest_max = find_max(lst[1:])
if lst[0] > rest_max:
return lst[0]
>>> find_max([1, 9, 3])