首页 > 解决方案 > 回文问题 - 尝试检查 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")   

标签: python-3.x

解决方案


尽管您有评论first_half并且second_half是您输入的子字符串,而不是列表。当您将它们打印出来时,您会将它们转换为列表,但在比较中,您不会转换first_halfreversed(second_half). 因此,您将字符串与迭代器(由 返回reversed)进行比较,该迭代器始终为假。

因此,一个基本的解决方法是对 进行转换if,就像您在打印列表时所做的那样:

if list(first_half) == list(reversed(second_half)):

更好的解决方法可能是作为字符串进行比较,方法是让其中一个切片使用 a stepof -1,因此您不需要使用reversed. 尝试second_half = the_string[-1:x//2:-1](或类似的,您可能需要将偶数或奇数调整一个)。或者,您可以在将字符串从输入中切出后使用“外星人笑脸”切片来反转字符串:second_half = second_half[::-1]

您的代码中还有其他一些奇怪之处,例如您的for i in range(x)循环会覆盖除最后一个之外的所有结果。只需x - 1在切片代码中使用,您根本不需要那个循环。你打电话int的频率也比你需要的多得多(如果你用//代替/,你可以摆脱所有的int电话)。


推荐阅读