python解决方案中超过了时间限制

时间:2019-12-13 08:07:19

标签: python python-3.x error-handling

我正在尝试解决Leetcode问题Happy Number,但似乎陷入了一个奇怪的时限超出错误。

我的代码:

class Solution:
    def isHappy(self, n: int) -> bool:
        def simu(n):
            sums = 0
            while n>0:
                s = n%10
                n = n//10
                sums=sums+(s**2)
            if sums != 1:
                simu(sums)
            return True
        while True:
            try:
                return simu(n)
            except RecursionError:
                return False

有什么办法解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

尝试直到获得RecursionError是一个非常糟糕的主意。相反,我能想到的一种解决方案是,跟踪以前失败的号码,并在获得已经失败的号码后立即停止进一步的尝试。因为,您确定肯定会再次发生相同的事情。

class Solution:
    def transform(self, n: int) -> int:
        s = 0
        while n > 0:
            d = n % 10
            s += d * d
            n = n // 10
        return s

    def isHappy(self, n: int) -> bool:
        failed_hist = set()  # maybe you can preload this with some already known not-happy numbers
        while n not in failed_hist:  # continue as long as `n` has not failed before
            if n == 1:
                return True
            failed_hist.add(n)  # remember this failed !
            n = self.transform(n)  # transform `n` to it's next form
        return False  # loop broke, i.e. a failed `n` occured again

这个想法是要演示一种解决方案,而不要强加于人。也许会有更好的解决方案,例如如果那些快乐的数字具有某些特殊的数学性质,等等...