场景:
我在做一个关于Leetcode的问题叫做nth丑陋数字。该算法是求素数仅包括1、2、3和5的第n个数。
我创建了一个被接受并通过了所有测试的解决方案。然后,我想用蟒蛇回忆录练习回忆录,但是回忆录出了问题。它适用于我自己的个人测试,但Leetcode不接受答案。
回忆录守则详见下文:
class Solution:
uglyNumbers = [1, 2, 3, 4, 5]
latest2index = 2
latest3index = 1
latest5index = 1
def nthUglyNumber(self, n: int) -> int:
while len(self.uglyNumbers) <= n:
guess2 = self.uglyNumbers[self.latest2index] * 2
guess3 = self.uglyNumbers[self.latest3index] * 3
guess5 = self.uglyNumbers[self.latest5index] * 5
nextUgly = min(guess2, guess3, guess5)
if(nextUgly == guess2):
self.latest2index += 1
if(nextUgly == guess3):
self.latest3index += 1
if(nextUgly == guess5):
self.latest5index += 1
self.uglyNumbers.append(nextUgly)
return self.uglyNumbers[n-1]我在回忆录中所做的唯一改变是使uglyNumbers、latest2index等成为类成员,而不是局部变量。
问题:
当我向LeetCode提交时,它声称解决方案不再有效。这就是它的断裂之处:
输入12 /输出6/预期16
但是,当我自己测试代码并提供输入12时,它会给出预期的输出16。
下面是我所做的测试,以确认该算法似乎像预期的那样工作:
# This code goes inside Class Solution
def nthUglyNumber(self, n: int) -> int:
print("10th: " + str(self.nthUgliNumber(10)))
print("11th: " + str(self.nthUgliNumber(11)))
print("12th: " + str(self.nthUgliNumber(12)))
print("9th: " + str(self.nthUgliNumber(9)))
print("14th: " + str(self.nthUgliNumber(14)))
print("10th: " + str(self.nthUgliNumber(10)))
print("11th: " + str(self.nthUgliNumber(11)))
print("12th: " + str(self.nthUgliNumber(12)))
return self.nthUgliNumber(n)
def nthUgliNumber(self, n: int) -> int:
# The regular definition of nthUglyNumber goes here我想知道的
在Python回忆录中是否有一些我没有看到的导致代码出错的边缘情况?还是完全是Leetcode的错?我知道我的算法可以在没有回忆录的情况下工作,但我想了解哪里出了问题,这样我就能更好地理解Python,从而避免将来出现类似的错误。我很感激你的帮助!
发布于 2021-01-17 11:00:09
我相信leetcode可能正在使用解决方案类的单独实例在多个线程上并行运行所有测试。由于您将nthUgliNumber存储为类变量,实例可能以冲突的方式更新它(和3个索引)。
从leetcode的角度来看,每个测试都不会产生影响其他测试的副作用。因此,在不同的实例中并行执行是合法的。超出测试用例范围的缓存可能是不可取的,因为它会使性能度量不一致,并且取决于测试用例的顺序和内容。
https://stackoverflow.com/questions/65693435
复制相似问题