【发布时间】:2020-08-26 12:14:19
【问题描述】:
如果单词/行是回文,我想打印 True。 代码从文本文件中读取文本(使用 sys.argv[1])。 我不明白为什么它只检查第一行。
文本文件:
racecar
AddE
HmllpH
Was it a car or a cat I saw
Hannah
T can arise in context where language is played wit
Able was I ere I saw Elba
Doc note I dissent A fast never prevents a fatness I diet on cod
代码:
import sys
filename = sys.argv[1]
with open(filename, "r") as f:
text = f.readline().strip().lower()
while text:
palindrome = True
i = 0
while i < len(text) / 2:
if text[i] != text[len(text) - 1 - i]:
palindrome = False
i += 1
if palindrome:
print(True)
text = f.readline().strip()
输出:
True
【问题讨论】:
-
只有第一行是回文。无论哪种方式,您都可以使用
text == text[::-1]来检查是否回文 -
不确定是否与此有关,但您可以循环
for text in f:(并在循环中剥离和降低) -
另外,您的代码似乎运行良好,但在
False的情况下,您永远不会print,除了第一个之外,所有代码都是错误的,因为您永远不会lower那些。
标签: python python-3.x algorithm palindrome