Py学习  »  Python

在python中,如何在不传递count参数的情况下计算递归深度?

iliketocode • 5 年前 • 1311 次点击  

编写一个函数persistence,它接受一个正参数 n 并返回其乘法持久性,即必须将中的数字相乘的次数。 n个 直到你达到一位数。

例如:

我试过这段代码,但游戏规则是我不能传递两个参数。所以我必须消除 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
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/48197
 
1311 次点击  
文章 [ 1 ]  |  最新文章 5 年前
ggorlen
Reply   •   1 楼
ggorlen    6 年前

如果希望保持算法不变,可以使用默认参数:

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))