0

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.

R891
  • 2,550
  • 4
  • 18
  • 30
  • What hostility? The duplicate looks essentially the same to me. – showdev Oct 01 '15 at 23:22
  • Many people will not find the other answer based on its title. I didn't, even after searching quite a bit. SO is an incredibly useful resource, but it's very frustrating to use. I think it took me three years just to be able to write a comment to help someone out when an answer. It's kind of like Wikipedia -- very useful, but with over-zealous moderation. Sites like this are the long-tail of information. Someone searching Google with the other keywords will find the other post, and someone searching with these keywords will find this post. No need to downvote. SO won't run out of disk space. – R891 Oct 02 '15 at 00:49

1 Answers1

2

The problem is that you forgot to add a return statement on the second if and else cases.

The following should work:

def find_lowest(lst):
    """Return the lowest positive number in a list."""
    def lowest(first, rest):
        # Base case
        if len(rest) == 0:
            return first
        if first > rest[0] or first < 0:
            return lowest(rest[0], rest[1:])
        else:
            return lowest(first, rest[1:])
    return lowest(lst[0], lst[1:])

a = [6, -4, 4, 8, -127, 5, 7, 2, 3, 9]
Nir Alfasi
  • 53,191
  • 11
  • 86
  • 129