首页 > 解决方案 > 如何计算递归深度而不在 Python 中传递计数参数?

问题描述

编写一个函数,持久性,它接受一个正参数n并返回其乘法持久性,这是您必须将数字相乘n直到达到单个数字的次数。

例如:

我已经尝试过这个有效的代码,但游戏的规则是我不能传递 2 个参数。所以我必须消除这个counter论点。

def persistence(n,counter): #recursion

    n = list(str(n))
    product = 1

    for i in n:
        product *= int(i)

    if product < 10:
        return counter+1

    else:
        counter +=1
        return persistence(product,counter)
persistence(39) # returns 3, because 3*9=27, 2*7=14, 1*4=4
                 # and 4 has only one digit

标签: pythonrecursion

解决方案


如果您想保持算法相同,可以使用默认参数:

def persistence(n, counter=0):
    product = 1

    for i in str(n):
        product *= int(i)

    if product < 10:
        return counter + 1

    return persistence(product, counter + 1)

print(persistence(39))

话虽如此,正如@TomKarzes 指出的那样,根本不需要counter参数(或递归)——将结果传回调用堆栈而不是向上。任何给定的调用都不需要来自先前调用的任何信息,除了n自身的当前状态来确定持久性。

def persistence(n):
    product = 1

    for i in str(n):
        product *= int(i)

    if product < 10:
        return 1

    return persistence(product) + 1

print(persistence(39))

推荐阅读