首页 > 解决方案 > 回文比较未检测到某些情况

问题描述

如果单词/行是回文,我想打印 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

标签: pythonpython-3.xalgorithmpalindrome

解决方案


  1. 为什么只打印第一行?

只有第一行是区分大小写的回文。

  1. 代码修复:

关于你所看到的一些解释:

2.1。loop for text in map(str.strip, f),意味着我们正在遍历文件f行并将该str.strip()方法应用于每个行。

2.2. text.upper()将文本转换为统一的大写,以进行通用比较。

2.3. text_upper[::-1]反转文本:奇怪的[::-1]索引表示法,意味着我们将所有元素向后移动一步(因此 -1)。

import sys
filename = 'outfile.txt'

with open(filename, "r") as f:
    for text in map(str.strip, f):
        text_upper = text.upper()
        if text_upper == text_upper[::-1]:
            print(f'{text} is palindrom!')

推荐阅读