ikebukuru
ikebukuru

Reputation: 89

Recursion in Python using function parameter to keep track but return value going missing

When recursively passing this string into this counting function, and declaring a set as a mutable function parameter to keep track of the results through the recursion, everything seems to work fine when stepping through with a debugger (and also by the print statements in the end test case), however the return result is None. What's going on here that's causing that?

def count_ways(data, l = set()):
    if len(data) == 0:
        print(l)        # Shows my set has stuff
        print(len(l))   # Shows my set has length
        return(len(l))  # Why is None being returned?!
    one_dig = int(data[:1])
    two_digs = int(data[:2])
    if (one_dig > 0):
        l.add(one_dig)
    if (10 <= two_digs <= 26):
        l.add(two_digs)
    count_ways(data[1:])

print(count_ways("124136"))

Upvotes: 3

Views: 60

Answers (1)

Mark
Mark

Reputation: 92440

You need to return from the non-edge condition as well.

def count_ways(data, l = set()):
    if len(data) == 0:
        print(l)        # Shows my set has stuff
        print(len(l))   # Shows my set has length
        return(len(l))  # Why is None being returned?!
    one_dig = int(data[:1])
    two_digs = int(data[:2])
    if (one_dig > 0):
        l.add(one_dig)
    if (10 <= two_digs <= 26):
        l.add(two_digs)
    return count_ways(data[1:]) # return this!!

print(count_ways("124136"))

Just in case you're interested in another option, you don't really need the argument. You can just return the union of a local set with the result of the recursion:

def count_ways(data):
    l = set()
    if len(data) == 0:
        return l  
    one_dig = int(data[:1])
    two_digs = int(data[:2])
    if (one_dig > 0):
        l.add(one_dig)
    if (10 <= two_digs <= 26):
        l.add(two_digs)
    return l | count_ways(data[1:])

print(count_ways("124136"))
# {1, 2, 3, 4, 6, 12, 13, 24}

Upvotes: 3

Related Questions