0

It is my intention to recursively multiply two numbers with this function. I realize this is quite possibly far from optimal. Why does my call, print rec_mult(15, 1111), to this function print None rather than 16665?

def rec_mult(x, y, tot=0, inc=0):
    if int(x) ==  0:
        return tot
    else:
        x = str(x)
        tot += int(x[(-1+inc):]) * y
        x = x[:(-1+inc)] + "0"; inc -= 1
        rec_mult(x, y, tot, inc)

1 Answer 1

5

You have to return when recursively calling your function like,

def rec_mult(x, y, tot=0, inc=0):
    if int(x) ==  0:
        return tot
    else:
        x = str(x)
        tot += int(x[(-1+inc):]) * y
        x = x[:(-1+inc)] + "0"; inc -= 1
        return rec_mult(x, y, tot, inc)  # <-- return here

print rec_mult(2, 10)  # 20
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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