gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 09:05:24 25 4
gpt4 key购买 nike

我正在尝试解决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

任何想法如何克服这个?

最佳答案

尝试直到获得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

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

关于python - python解决方案中超过了时间限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59318470/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com