3

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"))

1 Answer 1

3

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}
Sign up to request clarification or add additional context in comments.

7 Comments

Say whaaaa? I'm relatively new to Python, but... isn't return, well, return? Am I not actually out of the function's stack on the first one? If not, why does it even print None? Confused!
I know @ikebukuru - recursion can be a little mind bending. You are calling the function several times so you need to return from the inner and outer calls.
cool; thanks for such a quick response; cool profile pic and hope you and yours are okay up there in AK after the quake!
Thanks @ikebukuru, still a little shellshocked but safe.
@ikebukuru if you've found this answer helpful, please consider marking it as accepted. :-)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.