【问题标题】:Happy Number Function Won't Return True快乐数字函数不会返回真
【发布时间】:2017-05-23 07:24:58
【问题描述】:

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。为什么会发生这种情况,我该如何解决?顺便说一句,如果这可能很重要,该函数是递归的。

【问题讨论】:

  • 您在 happyNum 函数中缺少返回语句 return happyNum(newNum)
  • 那应该去哪里?
  • elsehappyNum 函数中。顺便说一句,如果输入不是一个快乐的数字,你将在你的函数中得到一个无限循环。
  • 我将 else 语句更改为“else: return happyNum(newNum)”,但它仍然没有返回 True
  • happyNum 的任何调用中,c 设置为空列表是否正常?

标签: python recursion return


【解决方案1】:

视频对快乐数字的描述不完整。快乐的数字会以 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 的时间内确定多达 100 万个数字的幸福度,而如果我们没有记录之前的快乐和不快乐的数字!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-02
    • 1970-01-01
    • 2013-03-25
    • 2011-02-14
    相关资源
    最近更新 更多