【问题标题】:Unexpected python recursive multiplication return意外的python递归乘法返回
【发布时间】:2013-07-02 23:03:59
【问题描述】:

我打算用这个函数递归地将两个数字相乘。我意识到这很可能远非最佳。为什么我对这个函数的调用 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)

【问题讨论】:

    标签: python recursion return-value multiplication


    【解决方案1】:

    当递归调用你的函数时,你必须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
    

    【讨论】:

      猜你喜欢
      • 2017-08-31
      • 2019-10-07
      • 1970-01-01
      • 2014-01-24
      • 2018-10-16
      • 2016-02-02
      • 2012-12-11
      • 1970-01-01
      • 2019-09-12
      相关资源
      最近更新 更多