Let’s develop a recursive implementation for min
, named rec_min
, that takes
as a parameter a non-empty list (i.e., the input has at least one element):
Define the function header, including the parameters
def rec_min(a_list)
"""
Returns the minimum value in a non-empty list
"""
Define the recursive case
The minimum value is the lesser of the first element and the recursive minimum of the rest of the list, i.e.
min_rest = rec_min(a_list[1:])
if min_rest < a_list[0]:
return min_rest
else:
return a_list[0]
Define the base case
The minimum value of a list of length 1 is just the one and only value in the list
Put it all together
def rec_min(a_list):
if len(a_list) == 1:
return a_list[0]
else:
min_rest = rec_min(a_list[1:])
if min_rest < a_list[0]:
return min_rest
else:
return a_list[0]