【发布时间】:2015-05-17 15:08:57
【问题描述】:
我用 python 编写了一个简单的程序来检查句子是否是回文。但我不知道为什么它不起作用。结果总是假的。有谁知道怎么回事?
def isPalindrome(word):
# Removes all spaces, and lowercase the word.
word = word.strip().lower()
word = word.replace(" ", "")
# If the length of the word is less than 1, means its a palindrome
if (len(word) <= 1):
return True
# Compares the first and the last character of the word.
# If it is the same, calls the function again with the same word,
# without its first and last characters. If its not the same, its
# not palindrome
else:
if word[0] == word[-1]:
isPalindrome(word[1:-1])
else:
return False
sentence = input("Enter a sentence: \n")
if (isPalindrome(sentence)):
print("The sentence %s is palindrome." % sentence)
else:
print("The sentence %s is NOT palindrome" % sentence)
【问题讨论】:
-
你说函数总是返回
False,但这是不正确的,不是完全正确的......如果你尝试用print(isPalindrome(sentence))替换你的最后四个语句,你会看到你打印的两种可能的结果是不同的...... -
你写的代码的问题是,当你最终将字符串缩小到 0 或 1 时,它返回 True 回到递归函数的前一个化身,这不能保证最终函数的返回将为 True。但是,是的,使用 MattDMo 的代码!
标签: python recursion palindrome