快乐号码功能不会回归真实

时间:2017-01-09 04:45:11

标签: python recursion return

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

在观看链接的视频" 7和Happy Numbers"后,我决定写一些代码来检查给定的号码是否是一个满意的数字。

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 个答案:

答案 0 :(得分:0)

视频在对快乐数字的描述中不完整。幸福的数字会在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!")

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

def is_happy(number, seen=None, happy=set([1]), unhappy=set()):

    if seen is None:
        seen = set()

    if number in happy:  # it's happy
        happy.update(seen)  # all seen numbers are happy too
        return True

    if number in unhappy or number in seen:  # a cycle, it's unhappy
        unhappy.update(seen)  # all seen numbers are unhappy too
        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

for number in range(1, 1000001):
    if is_happy(number):
        print(number, end=" ")
print()

我们可以在1/6的时间内确定数字高达百万的幸福感,而不是我们没有跟踪以前的快乐和不快乐的数字!