【问题标题】:How can I make sure a word is palindrome using Python while using recursion?如何在使用递归时使用 Python 确保单词是回文?
【发布时间】: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


【解决方案1】:

发生这种情况是因为您将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] 反转字符串。它更干净,您不必使用递归。但是,上述修复也将帮助您处理递归位。

【讨论】:

    【解决方案2】:

    尝试以下方法:

    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] 反转单词。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-20
      • 2021-01-14
      • 2012-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-10
      • 1970-01-01
      相关资源
      最近更新 更多