python-3.x - 回文问题 - 尝试检查 2 个列表是否相等 python3.9
问题描述
我正在编写一个程序来检查给定的用户输入是否是回文。如果是程序应该打印“是”,如果不是“否”。我意识到这个程序太复杂了,因为我实际上只需要使用 reversed() 函数检查整个单词,但我最终通过将单词分成两个列表然后相互检查列表来使它变得非常复杂。
尽管如此,我不清楚为什么当我将“racecar”作为输入传递时,最后一个条件没有返回预期的“是”。当我在第 23 行和第 24 行打印列表时,我得到两个相同的列表,但是当我在条件中比较它们时,我总是得到“否”,这意味着它们彼此不相等。谁能解释这是为什么?我试图将列表转换为字符串,但没有运气。
def odd_or_even(a): # function for determining if odd or even
if len(a) % 2 == 0:
return True
else:
return False
the_string = input("How about a word?\n")
x = int(len(the_string))
odd_or_even(the_string) # find out if the word has an odd or an even number of characters
if odd_or_even(the_string) == True: # if even
for i in range(x):
first_half = the_string[0:int((x/2))] #create a list with part 1
second_half = the_string[(x-(int((x/2)))):x] #create a list with part 2
else: #if odd
for i in range(x):
first_half = the_string[:(int((x-1)/2))] #create a list with part 1 without the middle index
second_half = the_string[int(int(x-1)/2)+1:] #create a list with part 2 without the middle index
print(list(reversed(second_half)))
print(list(first_half))
if first_half == reversed(second_half): ##### NOT WORKING BUT DONT KNOW WHY #####
print("Yes")
else:
print("No")
解决方案
尽管您有评论first_half
并且second_half
是您输入的子字符串,而不是列表。当您将它们打印出来时,您会将它们转换为列表,但在比较中,您不会转换first_half
或reversed(second_half)
. 因此,您将字符串与迭代器(由 返回reversed
)进行比较,该迭代器始终为假。
因此,一个基本的解决方法是对 进行转换if
,就像您在打印列表时所做的那样:
if list(first_half) == list(reversed(second_half)):
更好的解决方法可能是作为字符串进行比较,方法是让其中一个切片使用 a step
of -1
,因此您不需要使用reversed
. 尝试second_half = the_string[-1:x//2:-1]
(或类似的,您可能需要将偶数或奇数调整一个)。或者,您可以在将字符串从输入中切出后使用“外星人笑脸”切片来反转字符串:second_half = second_half[::-1]
。
您的代码中还有其他一些奇怪之处,例如您的for i in range(x)
循环会覆盖除最后一个之外的所有结果。只需x - 1
在切片代码中使用,您根本不需要那个循环。你打电话int
的频率也比你需要的多得多(如果你用//
代替/
,你可以摆脱所有的int
电话)。
推荐阅读
- amazon-web-services - 如何访问 AWS 私有存储桶
- java - 如何将字符串数组添加到具有非标准类的队列中?
- xcode - iOS 13.4 beta 上的编辑崩溃?
- javascript - 反应选择 - 缓冲 onChange 事件
- sas - 微距分辨率
- pandas - 基于可变长度的 Pandas 数据框列中的索引列表
- node.js - 如何在平均堆栈(Node.js + Mongodb)上的用户身份验证中检查当前登录的用户?
- kubernetes - 对 Helm 依赖项使用 values-production.yaml 而不是 values.yaml
- r - 通过函数保存数据集,但之后没有加载
- c# - C# TcpListener 是否仅限于局域网或我的代码有问题?