【发布时间】:2015-10-25 21:31:13
【问题描述】:
我需要编写一个函数来确定给定字符串是否为回文。以下是我目前写的:
def isPalindrome(string):
found = False
for i in range(len(string)):
if string[i] == string[len(string) - 1 - i]:
found = True
if found == True:
print("Inserted string is a palindrome. ")
else:
print("Inserted string is not a palindrome. ")
return
我遍历字符串,并检查前向和后向迭代是否给出相同的字符。但是如果我通过执行 isPalindrome("hello") 来应用这个程序,它会说这是一个回文。它没有给我正确的输出。有人可以指出我犯的任何错误,以便我从中吸取教训。
【问题讨论】:
-
检查字母是否不匹配。一旦发生这种情况,就断定这不是回文。
-
如果 any 镜像字符对匹配,则您将 found 设置为 True。相反,您希望 True 是 所有 镜像对匹配。因此将其初始化为 True,然后在循环中将其设置为 False,如果它们 不 匹配。
标签: python