如何解决如何在使用递归时使用 Python 确保单词是回文?
我正在尝试创建一个代码,其中 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()
解决方法
发生这种情况是因为您已将 new_word
设置为空字符串,然后您将 reverse()
的结果存储在另一个名为 result
的变量中。
这应该可以解决您的问题:
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:
# change here to result
print("Sorry,",result,"is NOT a palindrome")
或者,您可以使用 choice[::-1]
来反转字符串。它更干净,您不必使用递归。但是,上述修复程序也将帮助您处理递归位。
尝试以下操作:
def check_palindrome(word): # Creating function with 1 parameter: word
if word == word[:: -1]: # word[:: -1] reverses a string
return True # Return a true value if word is the same when reversed
else:
return False # Otherwise,return a false value
print(check_palindrome("racecar")) # Palindrome
print(check_palindrome("hello world")) # Not a palindrome
语法 word[:: -1]
反转单词。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。