使用 Python 测试回文时输出不正确



我正在编写一个程序,使用列表使用Python识别回文。但是,我的程序总是声明输入词是回文,即使它显然不是


word = input("Type a word, and I'll tell you if it's a palidrome or not: ")
word = " ".join(word)
new_word = word.split() #forms a list from user-inputted word
print(new_word)
variable = new_word
variable.reverse() #reverses word list 
print(variable)
if variable == new_word:
print("This is a palidrome")
else:
print("This is not a palidrome")

variable == new_word始终为真的原因是,在这种情况下,赋值运算符只是创建一个新指针,而不是一个新列表。

换句话说,variable = new_word不会创建列表的副本 - 它使variable指向内存中的同一列表。 所以当你反转variable时,你实际上是在反转原始列表。 如果在运行variable.reverse()打印new_word,则可以看到这一点。

本文是对指针的有用介绍,本文很好地解释了赋值、浅拷贝和深拷贝。由于您的列表只是一个字符串列表,因此浅拷贝可以解决问题。[1] 深拷贝是矫枉过正的,但它也有效。

浅拷贝:

variable = list(new_word)

对于 Python 3.3 及更高版本,列表具有内置的copy方法:

variable = new_word.copy()

另一种选择是使用切片,但不提供起始或结束索引:

variable = new_word[:]

最后,copy模块提供了一个用于创建浅拷贝的函数:

variable = copy.copy(new_word)

深拷贝:

import copy
variable = copy.deepcopy(new_word)

[1] 虽然 mrtnlrsn 说你做了一个浅层的副本,但事实并非如此,正如链接的文章所解释的那样。

variablenew_word列表的浅拷贝,所以variable也是颠倒的(因为它指的是同一个列表) . 尝试使用

variable = copy.deepcopy(new_word)

您也可以通过反转输入字符串直接获得结果,使用以下代码:-

word = input("Type a word, and I'll tell you if it's a palidrome or not: ")
new_word = list(reversed(word))  #Reversing the string
new_word = ''.join(new_word)  # Converting list into string
if word == new_word :
print("This is a palidrome")
else:
print("This is not a palidrome") 

我已经对您的代码进行了更改:-

word = input("Type a word, and I'll tell you if it's a palidrome or not: ")
word = " ".join(word)
new_word = word.split() #forms a list from user-inputted word
print(new_word)
variable = new_word.copy()   # This is the change I have made.
variable.reverse() #reverses word list 
print(variable)
if variable == new_word:
print("This is a palidrome")
else:
print("This is not a palidrome")

我希望它能帮助你。

您需要替换

variable = new_word

variable = new_word[:]

这将创建变量的正确副本,您可以独立操作。

最新更新