Python 回文程序不工作

Python palindrome program not working

我在 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)

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

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 word[0] == word[-1]:
    isPalindrome(word[1:-1])

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

您需要将 "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)

你的算法没问题,唯一的问题是你没有return通过递归得到真正的结果,递归调用时你必须return isPalindrome 结果:

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

我认为这是一个赋值并且递归是必要的,显然 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 因此递归结束并且函数 returns Trueword[0] == word[-1] 将是 False 因此函数将 return 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)

由于已经解释了错误并且已经采取了明显的 s == s[::-1],所以我将把原始版本的可能最小版本放入组合中:

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

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

在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

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

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

让我们再看一个例子:

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