【问题标题】:palindrome program, from text file python回文程序,来自文本文件 python
【发布时间】:2015-01-18 17:08:30
【问题描述】:

我必须编写一个程序来测试输入字符串是否为回文。回文是一个单词序列,其读法与反向序列相同,例如单词“noon”。 方案要求如下:

  • 您必须使用堆栈
  • 程序应忽略除字母以外的所有字符。
  • 文件输入
  • 测试单个单词和完整的句子
  • 应该有一些真假结果。

到目前为止,这是我的代码:

f = open('myTextFile.txt', "r")    
line = f.readline()

while line:    
      print(line)    
      line = f.readline()    
      exclude = set("-")    
      line = ''.join(ch for ch in line if ch not in exclude)    
      exclude = set(",")    
      line = ''.join(ch for ch in line if ch not in exclude)    
      exclude = set(".")    
      line = ''.join(ch for ch in line if ch not in exclude)    
      exclude = set(" ")    
      line = ''.join(ch for ch in line if ch not in exclude)

f.close()

我的问题是接下来要做什么,我有点迷茫,我删除了所有多余的字符,我应该将每一行放入一个列表中以单独使用它们吗?你能指引我正确的方向吗?

【问题讨论】:

  • 执行此操作的经典方法是使用两个指针并检查每一对字符,直到它们指向同一位置或相互传递。您无需担心剥离标点符号;你可以让你的 incrementPointer 方法跳过非字母字符。

标签: python stack palindrome


【解决方案1】:

我不知道这对你有多大帮助,但为了检查回文,我会这样做:

# to get rid of spaces to check sentences (maybe repeat for punctuation marks) 
line = line.replace(" ","")  
# create reverse string see http://stackoverflow.com/questions/931092/reverse-a-string-in-python
reverse_line = line[::-1]
# check if it is a palindrome
print line == reverse_line

希望我能帮上一点忙

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-31
    相关资源
    最近更新 更多