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
When you do this, there is a new line character at the end, so your list is like:
the elements of which are obviously not a palindrome.
You need this:
So
stripthe newline character and it should be fine.To do this in one line:
EDIT: Iterating over a list and modifying it is causing problems. Use a list comprehension,as pointed out by Matthew.