【问题标题】:Python palindrome program not workingPython回文程序不起作用
【发布时间】: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


【解决方案1】:

你没有返回函数的结果。

替换:

if word[0] == word[-1]:
    isPalindrome(word[1:-1])

if word[0] == word[-1]:
    return isPalindrome(word[1:-1])

【讨论】:

    【解决方案2】:

    你让这种方式变得比它必须的更复杂:

    def palindrome(sentence):
        sentence = sentence.strip().lower().replace(" ", "")
        return sentence == sentence[::-1]
    

    sentence[::-1] 使用string slicing 反转字符串中的字符。

    显示上述return 语句的逻辑如何工作的稍微详细一点的解决方案:

    def palindrome(sentence):
        sentence = sentence.strip().lower().replace(" ", "")
        if sentence == sentence[::-1]:
            return True
        else:
            return False
    

    【讨论】:

    • 如果您将if 语句替换为return (sentence==sentence[::-1]),则更简单
    • 如果你删除了那个荒谬的 if-true-false 解决方案,你会得到我的支持:-P
    • @StefanPochmann 我重新安排了我的答案。我保留了更详细的版本来演示return 语句的逻辑,这对初学者会有帮助。赞成与否,由你决定。
    • 是的,对不起,我只是非常不喜欢这个结构,并感谢你的重新安排,虽然我真的不明白你的意思,它显示了它是如何工作的逻辑。 return 不评估事物的真实性,然后决定返回 True 或 False。这不是它是如何工作的。它只是简单地返回事物。
    【解决方案3】:

    你的算法很好,唯一的问题是你没有通过递归返回真正的结果,你必须在递归调用时返回isPalindrome结果:

    else:
        if word[0] == word[-1]:
            return isPalindrome(word[1:-1]) #this changed
        else:
            return False
    

    【讨论】:

      【解决方案4】:

      在 Python 中检查单词是否是回文的最佳方法如下:

      var[::] == var[::-1]
      

      但是,了解 Python 会在您执行 var[::-1] 时创建一个新的字符串副本非常重要,Python 内部不知道反向是否会产生相同的字符串。因此,它的编码方式是创建它的新副本。所以,当你尝试var[::1] is var[::-1] 时,你会得到FALSE

      例如:

      var = "RADAR" var1 = var[::] var is var1 True var2 = var[0:6:1] var is var2 True var3 = var[::-1] var is var3 False var4 = var[-1:-6:-1] var is var4 False var1 'RADAR' var2 'RADAR' var3 'RADAR' var4 'RADAR'

      在这里您可以看到,当您前进时,它不会创建“RADAR”的副本,它使用相同的引用。因为 PY 内部理解这个操作会产生相同的字符串对象。 但是,当您向后移动时,结果可能会有所不同。例如,如果我对“Ethans”进行相同的操作,那么它的反面将不一样。因此,PY 不知道反转字符串的结果是什么,它会创建它的新副本。

      因此,反向字符串使用“is”运算符返回错误值。

      这里还有一点需要注意。见下例:

      var = "abc" var1 = "abc" var is var1 True var = "Ethans Baner Pune" var1 = "Ethans Baner Pune" var is var1 False

      我们知道字符串是不可变的并且遵循Singleton DP,那么为什么第二种情况返回FALSE??

      这是因为 PY 不想在速度和性能上妥协。如果你写了一个很长的字符串并且它已经存在于内存中,那么 PY 应该引用相同的字符串。但是,发现长字符串需要很长时间并且性能会降低。因此,PY 不是引用现有字符串,而是创建一个新字符串。我们也对整数理解了这一点,它只遵循 Singleton DP 方法直到有限值(256)。

      让我们再看一个例子:

      var = "abcdefgh" var1 = "abcdefgh" var is var1 True var = "abcd efgh" var1 = "abcd efgh" var is var1 False

      【讨论】:

        【解决方案5】:

        您需要将“input”替换为“raw_input”。 此外,您正在递归调用 isPalindrome ,这里也有一个错误。应该是:

        if word[0] == word[-1]:
            return isPalindrome(word[1:-1])
        else:
            return False
        

        检查下面的更正代码:

        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
            if word[0] == word[-1]:
                return isPalindrome(word[1:-1])
            else:
                return False
        
        
        sentence = raw_input("Enter a sentence: \n")
        
        if (isPalindrome(sentence)):
            print("The sentence %s is palindrome." % sentence)
        else:
            print("The sentence %s is NOT palindrome" % sentence)
        

        【讨论】:

        • raw_input() 仅适用于 Python 2。input() 在 Py3 中等效。
        • 好的。我不知道,因为我只使用 Python 2。
        • @MattDMo 是 Py3 中可用的 raw_input
        • 不,不是。​​​​​​​​​​​​​​​
        【解决方案6】:

        我认为这是一个赋值并且递归是必要的,显然return word == word[::-1] 更简单但并不真正相关。您可以更简洁地编写递归函数:

        def isPalindrome(word):
            if not word:
                return True
            return word[0] == word[-1] and isPalindrome(word[1:-1])
        

        word[0] == word[-1] 将是TrueFalse,因此您将到达一个空字符串,其中not wordTrue 因此递归结束并且函数返回Trueword[0] == word[-1] 将是@ 987654330@ 所以函数将返回 False 因为 and isPalindrome(word[1:-1]) 永远不会被评估。

        我也可能会在函数之外进行降低:

        def isPalindrome(word):
            if not word:
                return True
            return word[0] == word[-1] and isPalindrome(word[1:-1])
        
        
        sentence = input("Enter a sentence: \n")
        sentence = sentence.strip().lower()
        sentence = sentence.replace(" ", "")
        if isPalindrome(sentence):
            print("The sentence %s is palindrome." % sentence)
        else:
            print("The sentence %s is NOT palindrome" % sentence)
        

        【讨论】:

          【解决方案7】:

          由于已经解释了错误并且已经采用了明显的s == s[::-1],因此我将仅将原始版本的可能最小版本放入混合中:

          def isPalindrome(s):
              s = s.strip().lower()
              return not s or s[0] == s[-1] and isPalindrome(s[1:-1])
          

          请注意,您不需要replace(" ", "")。外部空间现在用strip() 删除,内部空间将被strip() 删除,在更深入的递归调用中(如果我们不提前停止,因为s[0] == s[-1] 失败)。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2015-05-27
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2020-08-08
            • 1970-01-01
            相关资源
            最近更新 更多