Leetcode上的Python记忆失败

2024-09-30 06:26:19 发布

您现在位置:Python中文网/ 问答频道 /正文

场景:

我正在做一个关于Leetcode的问题,叫做n个丑陋的数字。该算法是寻找第n个数,其素数因子仅包括1、2、3和5

我创建了一个被接受并通过所有测试的解决方案。然后,我想用python对其进行记忆,以备练习——然而,记忆出现了一些问题。它适用于我自己的个人测试,但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时,它声称该解决方案不再有效。这里是它的断裂点:

Input 12 /// Output 6 /// Expected 16

然而,当我自己测试代码并为其提供输入12时,它给出了预期的输出16。即使我在12之前和之后用一堆不同的输入调用nthUglyNumber,它也会这样做,所以我不知道为什么测试用例在提交给LeetCode时会中断

以下是我执行的测试,以确认算法似乎按预期工作:

# 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,从而避免将来出现类似的错误。 我感谢你的帮助


Tags: 记忆self算法defintprintstrleetcode
1条回答
网友
1楼 · 发布于 2024-09-30 06:26:19

我相信leetcode可能正在使用解决方案类的单独实例在多个线程上并行运行所有测试。由于将nthUgliNumber存储为类变量,实例可能会以冲突的方式更新它(以及3个索引)

从leetcode的角度来看,每个测试都不会产生影响其他测试的副作用。因此,在不同实例中并行执行是合法的。超出测试用例范围的缓存可能是不可取的,因为它会使性能度量不一致,并且依赖于测试用例的顺序和内容

相关问题 更多 >

    热门问题