调试递归无法解决我的问题

问题描述 投票:0回答:1

我在下面用 Python 编写了这个函数,我期望看到结果 4,但却得到 2。这是为什么?

这是我的功能:

def persistence(n):
    if 0 <= n <= 9: 
        return n
    else:
        result = 0
        counter = 0
        while True:
            result += n % 10 * persistence(n // 10)
            counter += 1
            if result > 9:
                n = result
                result = 0
                continue
            return counter

print(persistence(999)) // Output should be 4 but gives me 2

我知道问题到底出在哪里。它在我写 result += n % 10 * persistence(n // 10) 的行中。当我在第一次迭代中调试它时,它没有给我数字 729(9 * 9 * 9 的乘法),而是给了我 18。为什么呢?我的代码有什么问题吗?在第一次迭代中,结果的输出不是 729,而是 18,因此 persistence(999) 的值不是我期望的值?

python recursion while-loop
1个回答
0
投票

不清楚你的功能应该做什么。

我最好的猜测是你想要将一个数字的数字相乘。

  • 在这种情况下,您要么使用没有 while 的递归,要么只是使用循环进行迭代。
def persistence(n):
    counter = 0
    result = 1
    while n:
        last_digit = n % 10
        result *= last_digit
        n //= 10
        counter += 1

    print(result)
    return counter


print(persistence(999))
print(persistence(9999))

打印

729
3
6561
4


© www.soinside.com 2019 - 2024. All rights reserved.