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

python解决方案中超出了时间限制,python,python-3.x,error-handling,Python,Python 3.x,Error Handling,我试图解决Leetcode问题,但我似乎陷入了一个奇怪的时间限制错误 我的代码: 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)

我试图解决Leetcode问题,但我似乎陷入了一个奇怪的时间限制错误

我的代码:

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

知道如何克服这个问题吗?

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

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

其目的是在不使用暴力手段的情况下演示解决方案。也许会有更好的解决方案,例如,如果那些快乐的数字有一些特殊的数学性质等等。

数字不快乐的情况是递归应该以相同的数字结束。至少我是这么认为的,也许你的递归需要太长的时间才能命中递归错误。如果数字不满意,问题不要求返回任何东西,但我仍然使用except RecursioneError处理错误。嗯,这意味着暴力方法对于Leetcode来说太慢。您可能需要考虑如何通过逐个查看数字来简化数学解。因此,您可以看出,如果任何数字返回自身,则表示其不满意。因为模式是重复的,我们可以估计在达到某个数字重复之前,会有一个有限的序列。所以我认为你不会因为保留一个比较器而面临内存问题。如果需要,请提供解决方案,但不确定该解决方案是否通过LEETCODE当为True时:
不是必需的