Python和回文 [英] python and palindromes
问题描述
最近,我通过的/ usr /共享/字典/所写循环的方法
并使用返回回文列表我的 ispalindrome(X)
方法
这里的一些code的...有什么错呢?它只是摊位10分钟,然后在文件中返回的所有单词列表
DEF逆转(一):
返回[:: - 1]高清ispalindrome(一):
B =反向(一)
如果b.lower()== a.lower():
返回True
其他:
返回FalseWL =开放('的/ usr /共享/字典/单词','R')
单词表= wl.readlines()
wl.close()
在单词表X:
如果不是ispalindrome(X):
wordlist.remove(X)
打印词表
词库= wl.readlines()
当你做到这一点,就在最后一个换行符,所以你的列表是这样的:
['眼\\ n','再见\\ n','CYC \\ n']
其中的元素是显然不是回文
您需要这样的:
['眼睛','再见','CYC']
所以条
换行字符,它应该是罚款。
要在一行做到这一点:
单词表= [line.strip()在开线('的/ usr /共享/字典/单词')]
编辑:遍历一个列表,并修改它导致的问题。使用列表COM prehension,如<一指出, href=\"http://stackoverflow.com/questions/4666339/python-and-palindromes/4666444#4666444\">Matthew.
i recently wrote a method to cycle through /usr/share/dict/words
and return a list of palindromes using my ispalindrome(x)
method
here's some of the code...what's wrong with it? it just stalls for 10 minutes and then returns a list of all the words in the file
def reverse(a): return a[::-1] def ispalindrome(a): b = reverse(a) if b.lower() == a.lower(): return True else: return False wl = open('/usr/share/dict/words', 'r') wordlist = wl.readlines() wl.close() for x in wordlist: if not ispalindrome(x): wordlist.remove(x) print wordlist
wordlist = wl.readlines()
When you do this, there is a new line character at the end, so your list is like:
['eye\n','bye\n', 'cyc\n']
the elements of which are obviously not a palindrome.
You need this:
['eye','bye', 'cyc']
So strip
the newline character and it should be fine.
To do this in one line:
wordlist = [line.strip() for line in open('/usr/share/dict/words')]
EDIT: Iterating over a list and modifying it is causing problems. Use a list comprehension,as pointed out by Matthew.
这篇关于Python和回文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!