Leetcode,在测试用例中有效,但在提交时无效

问题描述 投票:0回答:1

嗨,这是我在 StackOverflow 中的第一个问题,所以它可能并不完美。

我正在尝试使用 python3.10 从 leetcode 解决这个问题 https://leetcode.com/problems/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

--------------添加信息(错误和测试用例)---------------- 所以当提交代码时,我收到这样的错误。The error raised when submitted

所以我将其添加到测试用例部分并运行代码,它有效。same case works in test case

此外,它在问题中说代码将使用这样的命令运行

"Your Codec object will be instantiated and called as such:
 codec = Codec()
 codec.decode(codec.encode(url))"
python python-3.x class immutability
1个回答
0
投票

好的,谢谢大家的帮助。我不知道我做了什么,但现在有效了。我做的最后一件事是将随机素数(p 和 q)的范围从 (2~100) 更改为 (100~1000)。然后就成功了。

我不知道为什么,我认为这是我试图使用的 RSA 算法的数学原理。但它现在可以工作了。再次感谢gyus的帮助。

'''

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

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

    self.e = self.Gete(phi_n)

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

    self.n = n

    return str_encrp_url

'''

© www.soinside.com 2019 - 2024. All rights reserved.