在使用递归时,如何使用Python确保单词是回文的?

在使用递归时,如何使用Python确保单词是回文的?,python,recursion,input,reverse,Python,Recursion,Input,Reverse,我试图创建一个代码,python在其中要求用户输入或输入一个单词,并且它必须检查它是否是回文,是否使用递归。通过reverse()函数,如果单词不是回文,它将接收字符串,并通过递归,反向返回该字符串。似乎我能够接受输入,当我输入一个不是回文的单词时,它会返回所需的输出。但是,它不会以相反的方式返回单词,而且当我放入一个回文单词时,它也不会返回输入,在输出中留下空白 def reverse(choice, index, new_word): if index < 0:

我试图创建一个代码,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()
def reverse(选项、索引、新单词):
如果指数<0:
返回新单词
其他:
新单词+=选项[索引]
返回反向(选项,索引-1,新单词)
def palindrome():
new_word=“”
choice=input(“请输入一个单词以检查它是否是回文:”)
结果=反向(选择,透镜(选择)-1,新单词)
如果结果==选择:
print(“这个词”choice,“是回文”)
其他:
打印(“对不起”,新单词,“不是回文”)
回文

之所以发生这种情况,是因为您将
new\u 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]
反转单词。

您的代码应该反转字符串,还是检查它是否是回文?您可以通过反转字符串来检查字符串是否为回文,但该函数本身不会是递归的(对于检查字符串是否为回文的特定问题,有一个更简单的递归解决方案,它不涉及反转整个字符串).是的,只有在这种情况下不是回文时,它才应该反转刺。我是学习递归的新手,所以任何帮助都将不胜感激!