Reputation: 33
I am attempting to find palindromes from a generated list of anagrams. The twist here is that my initial input is a list of palindromes. I am essentially trying to automate a hunt for a palindrome that is an anagram of a palindrome (not homework, just an English nerd).
The original palindromes for input will come from 'pals.txt' where the palindromes are line-separated and have had spaces and non-numerical characters removed. I am using the British-English dictionary file 'dictionary.txt' to generate the anagrams.
I would appreciate any input as I am still very much a beginning programmer. Thank you!
def isPalindrome(s):
return s.lower() == s[::-1].lower()
def anagramchk(word,chkword):
for letter in word:
if letter in chkword:
chkword = chkword.replace(letter, '', 1)
else:
return 0
return 1
f0 = open('pals.txt', 'r')
f1 = open('dictionary.txt', 'r')
for line in f0:
wordin = line
for line in f1:
line = line.strip()
if len(line) >= 4:
if anagramchk(line, wordin):
if isPalindrome(line):
print line
f0.close()
f1.close()
Upvotes: 3
Views: 1077
Reputation: 113965
import collections
def isPalindrome(s):
return s.lower() == s[::-1].lower()
def anagramchk(word,chkword):
return sorted(word.lower()) == sorted(chkword.lower())
def allAnagrams(dictfilepath):
answer = collections.defaultdict(list)
with open(dictfilepath) as dictfile:
for line in dictfile:
word = line.strip().lower()
answer[''.join(sorted(word))].append(word)
return answer
def fetchAllAnagrams(wordin, anagrams):
return anagrams[''.join(sorted(wordin.lower()))]
def main(dictfilepath, palsfilepath):
anagrams = allAnagrams(dictfilepath)
with open(palsfilepath) as palfile:
for line in palfile:
word = line.strip().lower()
if isPalindrome(word):
for anagram in anagrams[''.join(sorted(word))]:
if isPalindrome(anagram):
print "%s is an anagram of %s" %(anagram, word)
Suppose your filepaths are 'path/to/dictfile'
and 'path/to/palsfile'
, then you could call main
as follows:
main('path/to/dictfile', 'path/to/palsfile')
Hope this helps
Upvotes: 2