0

この関数で 2 つの数値を再帰的に乗算することが私の意図です。これはおそらく最適とはほど遠いことだと思います。print rec_mult(15, 1111)この関数への呼び出し がNoneではなく出力されるのはなぜ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)
4

1 に答える 1

5

return関数を再帰的に呼び出すときは、次のようにする必要があります。

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
于 2013-07-02T23:05:19.570 に答える