英文:
Why does this piece of code have this edge case
问题
I was trying to try a palindrome test but a specific number 10022201, always returns true.
class Solution():
def isPalindrome(x):
if isinstance(x, int):
x = str(x)
for y in x:
index = x.index(y)
rev = x[::-1]
if x[index] != rev[index]:
b = bool(0)
break
else:
b = bool(1)
return b
x = 10022201
solution = Solution()
result = Solution.isPalindrome(x)
print(result)
帮助请!
英文:
I was trying to try a palindrome test but a specific number 10022201, always returns true.
class Solution():
def isPalindrome(x):
if isinstance(x, int):
x = str(x)
for y in x:
index = x.index(y)
rev = x[::-1]
if x[index] != rev[index]:
b = bool(0)
break
else:
b = bool(1)
return b
x = 10022201
solution = Solution()
result = Solution.isPalindrome(x)
print(result)
help please!
答案1
得分: 3
当你运行x.index(y)
时,它返回与y
匹配的x
中的第一个值的索引。因此,当你在第二个零上时,它返回第一个零的索引。
你可以改用以下方式:
class Solution():
def isPalindrome(x):
if isinstance(x, int):
x = str(x)
for index in range(len(x)):
rev = x[::-1]
if x[index] != rev[index]:
b = bool(0)
break
else:
b = bool(1)
return b
在这里,你遍历字符串中的所有可能的索引,然后检查每个对应的字符是否相等。基本上是你之前尝试做的事情,只是更简化。
此外,你可以直接检查字符串是否相等,将数字的字符串与其反转版本进行比较:
class Solution():
def isPalindrome(x):
if isinstance(x, int):
x = str(x)
rev = x[::-1]
return x == rev
英文:
When you run x.index(y)
, it returns the first value in x
that matches y
. Therefore, when you're on the second zero, it returns the index of the first zero.
What you can do instead is this:
class Solution():
def isPalindrome(x):
if isinstance(x, int):
x = str(x)
for index in range(len(x)):
rev = x[::-1]
if x[index] != rev[index]:
b = bool(0)
break
else:
b = bool(1)
return b
Here, you go through all the possible indeces in the string, and then you check if each corresponding character is equivalent. Basically what you were trying to do, just simplified.
Also, you can just check for string equality, comparing the string of the number to the reversed version of that:
class Solution():
def isPalindrome(x):
if isinstance(x, int):
x = str(x)
rev = x[::-1]
return x == rev
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论