Python3.9回文检测场景下拆分两列表判断相等的问题排查
问题根因
reversed() 是Python内置的迭代器生成函数,返回的是迭代器对象而非反转后的序列本身。你在打印时将reversed(second_half)和first_half都主动转为了list,所以能看到内容一致,但判断条件里直接用字符串first_half和迭代器对象做相等校验,二者类型都不匹配,必然返回False。
修复方法
只需要将判断条件的两侧转为相同类型再对比即可,可选两种写法:
- 统一转字符串对比:
if first_half == ''.join(reversed(second_half)):
- 统一转列表对比:
if list(first_half) == list(reversed(second_half)):
其他可优化点
- 奇偶分支下的
for i in range(x)属于完全冗余的无效代码,循环内每次给first_half、second_half赋的值完全相同,没有任何执行意义,直接删除循环保留内部的赋值语句即可。 odd_or_even函数可以直接简化为一行,无需额外的if判断:
def odd_or_even(a): return len(a) % 2 == 0
修复后完整可运行代码
def odd_or_even(a): return len(a) % 2 == 0 the_string = input("How about a word?\n") x = len(the_string) if odd_or_even(the_string): half = x // 2 first_half = the_string[:half] second_half = the_string[half:] else: half = (x - 1) // 2 first_half = the_string[:half] second_half = the_string[half+1:] if first_half == ''.join(reversed(second_half)): print("Yes") else: print("No")
内容的提问来源于stack exchange,提问作者dark_bambi
相关产品推荐
相关产品推荐

