【发布时间】:2021-03-31 19:48:27
【问题描述】:
我正在尝试创建一个代码,其中 python 要求用户输入或输入一个单词,并且它必须使用递归来检查它是否是回文。如果通过 reverse() 函数该单词不是回文,它将接收字符串,并通过递归反向返回该字符串。似乎我能够接受输入,当我输入一个不是回文的单词时,它会给我返回所需的输出。但是,它不会反向返回单词,而且当我输入一个回文单词并且它不会返回输入时,会在输出中留下空格。
def reverse(choice, index, new_word):
if index < 0:
return new_word
else:
new_word += choice[index]
return reverse (choice, index - 1, new_word)
def palindrome():
new_word = ""
choice = input("Please enter a word to check if it is palindrome:")
result = reverse(choice, len(choice) - 1, new_word)
if result == choice:
print("That word",choice,"IS a palindrome")
else:
print("Sorry,",new_word,"is NOT a palindrome")
palindrome()
【问题讨论】:
-
您的代码是否应该反转字符串,或者检查它是否是回文?您可以通过反转字符串来检查它是否是回文,但是该函数本身不会是递归的(对于检查它是否是回文的特定问题,有一个更简单的递归解决方案,它不涉及反转整个字符串) .
-
是的,只有在这种情况下它不是回文时,它才应该扭转刺痛。我是学习递归的新手,所以任何帮助都将不胜感激!
标签: python recursion input reverse