As an exercise, I'm trying to find the lowest positive number in a list using recursion in Python. This almost works, finding the 2 when it does print(first)
, but then it ends up returning None
. Is there a way to fix this code or am I on the wrong track?
def find_lowest(lst):
"""Return the lowest positive number in a list."""
def lowest(first, rest):
# Base case
if len(rest) == 0:
print(first) # This line is only to check the value
return first
if first > rest[0] or first < 0:
lowest(rest[0], rest[1:])
else:
lowest(first, rest[1:])
return lowest(lst[0], lst[1:])
a = [6, -4, 4, 8, -127, 5, 7, 2, 3, 9]
print(find_lowest(a)) # Prints None, but should print the lowest number
Edit: this question is not exactly the same as the other one. People searching for this kind of answer will not find the other one, because it is asking a similar question but in a very different way. Stack Overflow has useful content, but the hostility and downvoting are obnoxious.