首页 > 解决方案 > 陷入 CodeWars 问题.. 持久性错误问题

问题描述

我今天尝试解决 CodeWars 问题,问题说明是: 在此处输入图像描述

我试图解决这个问题的代码是:

def persistence(n):

count = 0
multi = 1

while n > 9:
    string = str(n)
    for i in string:
        operator = int(i)
        multi *= operator
    count += 1
    n = multi

return count

它通过了持久性(4)= 0,持久性(25)= 2,持久性(999)= 4的示例测试,但无法通过这个示例:持久性(39)= 3,我的代码给了我4而不是3 .我无法弄清楚示例输入 39 发生了什么。有人可以解释一下我的代码有什么错误吗?

标签: persistence

解决方案


由于我第一眼也看不到,所以我在pythontutor.com. 您的代码中唯一缺少的部分是在 while 循环结束时将您的“multi”变量重置为 1。

    def persistence(n):
        count = 0
        multi = 1

        while n > 9:
            string = str(n)
            for i in string:
                operator = int(i)
                multi *= operator
            count += 1
            n = multi
            multi = 1

        return count

推荐阅读