LeetCode回文数问题本地IDE运行正常,平台报错求解
LeetCode回文数题目代码适配问题
我在做LeetCode的「回文数」判断题,本地VS Code里写的代码能正常运行,但放到LeetCode IDE里就报错。我知道解法不是最优的,就想找出问题出在哪。
最初的代码
class Solution(object): def __init__(self, x: int): self.x = x def isPalindrome(self): main_list = [] converted_num = str(self.x) for x in converted_num: main_list.append(x) main_list.reverse() str1 = "" for ele in main_list: str1 += ele print(str1 == self.x) p1 = Solution("11511") p1.isPalindrome()
LeetCode报错信息
TypeError: __init__() takes exactly 2 arguments (1 given) ret = Solution().isPalindrome(param_1) Line 39 in _driver (Solution.py) _driver() Line 49 in <module> (Solution.py)
修改后的代码(移除__init__)
class Solution(object): def isPalindrome(self, x): orig = x main_list = [] converted_num = str(x) for x in converted_num: main_list.append(x) main_list.reverse() str1 = "" for ele in main_list: str1 += ele return (str1 == orig)
问题分析
初始代码报错原因:LeetCode的判题逻辑是直接调用
Solution类的isPalindrome方法,会自动传入待判断的数字参数,不会先调用带参数的构造函数__init__。你给Solution加了必须传参的__init__,但LeetCode驱动代码是用Solution().isPalindrome(param_1)的方式调用,所以触发了参数不匹配的错误。修改后的代码仍有问题:你把数字x转成字符串反转后得到
str1(字符串类型),但原变量orig是整数类型,整数和字符串直接比较永远不相等。需要把str1转回整数,或者把orig转成字符串再比较,比如改成return str1 == str(orig)。
内容的提问来源于stack exchange,提问作者Naveer
相关产品推荐
相关产品推荐

