Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"))
like image 233
ikebukuru Avatar asked Jul 27 '26 20:07

ikebukuru


1 Answers

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}
like image 58
Mark Avatar answered Jul 29 '26 09:07

Mark



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!