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。为什么会发生这种情况,我该怎么解决?顺便说一句,如果这可能很重要,函数是递归的。在
视频对快乐数字的描述不完整。快乐的数字最终会是1,但他们不会说不快乐的数字会发生什么。如果他们不高兴,他们最终会循环使用一系列数字。因此,要想发现他们是否不高兴,你必须跟踪他们的数字,看看你是否有重复。(大概是你有
c = []
的功能,但最后没有使用)这意味着你需要在递归调用中传递一个不断增长的集合。数字145、113和130一般不有用,不应该出现在代码中。在以下是针对上述问题的返工:
但是,如果我们找到一个快乐的数字,那么我们在确定它是否快乐的过程中检查过的所有数字本身都是幸福的。不愉快的数字也是如此。因此,如果我们添加一些缓存,使用传递到后续调用的危险默认值:
^{pr2}$我们可以在1/6的时间内判断出100万个数字的幸福程度,而不是我们没有记录之前的快乐和不快乐的数字!在
相关问题 更多 >
编程相关推荐