You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

LeetCode短网址编解码代码测试通过但提交失败求助

求解LeetCode《Encode and Decode TinyURL》提交报错问题

这是我在StackOverflow的第一个问题,可能表述不够完善。我正在使用Python3.10解决LeetCode的《Encode and Decode TinyURL》问题。我的代码在本地测试用例中可正常运行,但提交时会报错;然而将报错对应的测试用例添加到本地测试中,代码又能正常执行。我已按照LeetCode要求在类中添加__init__方法,并尽可能让encode和decode函数中的变量保持不可变(例如每次创建空列表并转换为字符串对象,确保函数返回字符串而非列表)。我已尝试多种方法仍未找到解决方案,恳请帮助。

附上代码:

import math, random

class Codec:
    def __init__(self):
        self.d = 3
        self.n = 0 

    def isprime(self, n):
        if n < 2:
            return False
        for i in range(2, n//2 + 1):
            if n % i == 0:
                return False
        return True

    def randprime(self, min, max):
        a = random.randint(min, max)
        while self.isprime(a) != True:
            a = random.randint(min, max)
        return a

    def Gete(self, phi_n):
        e = 3
        for i in range(phi_n-1):
            if math.gcd(e, phi_n) == 1:
                return e
            else:
                e += 1

    def Getd(self, e, phi_n):
        d = 3
        while True:
            if (1 - d*e) % phi_n == 0:
                return d
            else:
                d += 1

    def encode(self, shortUrl: str) -> str:
        p = self.randprime(2, 100)
        q = self.randprime(2, 100)
        while p == q:
            p = self.randprime(1000,5000)

        self.n = p*q
        phi_n = (p-1)*(q-1)

        e = self.Gete(phi_n)
        self.d = self.Getd(e, phi_n)

        as_url = []
        encryp_url = []
        as_url = [ord(ch) for ch in shortUrl]
        encryp_url = [pow(ch, e, self.n) for ch in as_url]
        str_encrp_url = "".join(chr(ch) for ch in encryp_url)

        return str_encrp_url
    
    def decode(self, longUrl: str) -> str:
        decryp_url = []
        asc_longUrl = [ord(ch) for ch in longUrl]
        decryp_url = [pow(ch, self.d, self.n) for ch in asc_longUrl]
        message = "".join(chr(ch) for ch in decryp_url)
        return message

补充信息:
提交时出现报错,但将该测试用例添加到本地测试后可正常运行。问题说明中提到代码会以如下方式调用:

Your Codec object will be instantiated and called as such:
 codec = Codec()
 codec.decode(codec.encode(url))

内容的提问来源于stack exchange,提问作者hiimnewb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 04:42:45