【问题标题】:why is function returning a different thing when called alone VS when called twice为什么单独调用时函数返回不同的东西VS调用两次时返回不同的东西
【发布时间】:2021-06-01 07:22:11
【问题描述】:

所以我有一个递归函数,我用不同的参数调用了 2 次,但我第二次调用它时,它没有给出正确的结果,它只在我第一次而不是第二次调用它时给出正确的结果。也许是内存或缓存问题?

def m(n):
    s= [int(char) for char in str(n)]
    product = 1
    for x in s:
       product *= x
    return product
i = 0
def persistence(n):
    global i
   
    if len(str(n)) == 1:
       return i
    else:
        j = m(n)
        i+=1
        s = persistence(j)
        return s 



print(persistence(39)) 
print(persistence(4)) #returns 3 when called with the top one but 0 when called alone



【问题讨论】:

  • 那是因为您使用 i 作为全局变量。再次执行持久化时,i变量值不为0
  • presistence(4) 将在if 分支中返回i。如果这是第一次调用persistence,那么i 就是0。如果您首先使用39 调用它,该调用将转到else 分支,该分支会更改i 变量。当您使用4 调用它时,它将不再是0。这就是为什么你应该避免全局的、可变的状态

标签: python python-3.x recursion memory


【解决方案1】:

您的函数持久化中有一个条件len(str(n)),因此如果n 是0 到9 之间的数字,则返回global i

当您单独调用print(persistence(4)) 时,您的函数返回global i(等于0)。

当你先调用print(persistence(39)),再调用print(persistence(4))时,第一次调用将global i设置为3,第二次调用juste返回global i的值值,即刚刚设置为3。

我真的不明白你想要做什么,但也许你的问题来自global的使用。

【讨论】:

    【解决方案2】:

    问题是您使用 i 作为全局变量。当您再次执行该方法时,您的 i

    def m(n):
        s= [int(char) for char in str(n)]
        product = 1
        for x in s:
           product *= x
        return product
    
    def persistence_recursive(n, i):
        if len(str(n)) == 1:
           return i
        else:
            j = m(n)
            i+=1
            s = persistence_recursive(j, i)
            return s 
    
    def persistence(n):
       return persistence_recursive(n, 0)
    
    
    
    print(persistence(39)) # returns 3
    print(persistence(4)) # returns 0
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-03-09
      • 2013-07-11
      • 2016-11-10
      • 1970-01-01
      • 1970-01-01
      • 2023-02-07
      • 2020-07-24
      相关资源
      最近更新 更多