快乐数字函数不会返回Tru

2024-10-08 22:22:47 发布

您现在位置:Python中文网/ 问答频道 /正文

https://www.youtube.com/watch?v=kC6YObu61_w

在看了“7和快乐数字”的链接视频后,我决定写一点代码来检查给定的数字是否是一个快乐数字。在

c = []
num = int(input("What number would you like to check? "))
def happyNum(n):
    newNum = 0
    c = []
    a = str(n)
    for b in a:
        c.append(int(b))
    for d in c:
        newNum = newNum + d**2
    if newNum <= 1:
        return True
    elif newNum == 145:
        return False
    elif newNum == 113:
        return False
    elif newNum == 130:
        return False
    else:
        happyNum(newNum)
if happyNum(num) == True:
    print("You've found yourself a happy number!")
elif happyNum(num) == False:
    print("Not a happy number I'm afraid!")

我用7测试了一下,从视频中我知道这是一个幸运数字,结果发现什么都没有打印出来。我做了一些测试,功能运行良好。一旦它达到1,它就进入if语句。唯一的问题是它永远不会返回True。为什么会发生这种情况,我该怎么解决?顺便说一句,如果这可能很重要,函数是递归的。在


Tags: infalsetruenumberfor视频returnif
1条回答
网友
1楼 · 发布于 2024-10-08 22:22:47

视频对快乐数字的描述不完整。快乐的数字最终会是1,但他们不会说不快乐的数字会发生什么。如果他们不高兴,他们最终会循环使用一系列数字。因此,要想发现他们是否不高兴,你必须跟踪他们的数字,看看你是否有重复。(大概是你有c = []的功能,但最后没有使用)这意味着你需要在递归调用中传递一个不断增长的集合。数字145、113和130一般不有用,不应该出现在代码中。在

以下是针对上述问题的返工:

def is_happy(number, seen=None):

    if number == 1:  # it's happy
        return True

    if seen is None:
        seen = set()

    if number in seen:  # a cycle, it's unhappy
        return False

    seen.add(number)

    # separate the digits into a list; several ways to do this
    digits = [ord(digit) - ord('0') for digit in str(number)]

    number = 0  # we can reuse number as we got what we needed

    for digit in digits:
        number += digit ** 2

    return is_happy(number, seen)  # this could have also been a loop

number = int(input("What number would you like to check? "))

if is_happy(number):
    print("You've found yourself a happy number!")
else:
    print("Not a happy number I'm afraid!")

但是,如果我们找到一个快乐的数字,那么我们在确定它是否快乐的过程中检查过的所有数字本身都是幸福的。不愉快的数字也是如此。因此,如果我们添加一些缓存,使用传递到后续调用的危险默认值:

^{pr2}$

我们可以在1/6的时间内判断出100万个数字的幸福程度,而不是我们没有记录之前的快乐和不快乐的数字!在

相关问题 更多 >

    热门问题