Friday, October 15, 2010

Python - Anagram generator

# python anagram generator 
# 
# This anagram generator uses a 
# text file as a reference for 
# appropriate words. 
# 
# The word file I used is in the 
# following format (each word has 
# it's own line): 
# 
# act 
# addition 
# adjustment 
# advertisement 
# after 
# again 
# against 
# ... and on and on... 
# 
 
def isAnagramOf(attempt, original):
    # all the same case 
    attempt = attempt.strip()
    if len(attempt) < 1: # only actual words 
        return False
    attempt, original = attempt.lower(), original.lower()
    for character in attempt:
        position = original.find(character)
        if (position == -1):
            return False
        original = original.replace(character, '', 1)
    return True
 
def getAnagramsFor(text):
    anagrams = []
    wordlist = open("wordlist.txt", 'r')
    for line in wordlist:
        line = line.strip("\n") #strip the carriage return 
        if isAnagramOf(line, text):
            anagrams.append(line)
    return anagrams
 
matching_anagrams = getAnagramsFor("pythonic prose")
print(len(matching_anagrams), "total anagrams generated")
for ana in matching_anagrams:
    print(ana)
 
 
# my output: 
# 
# 66 total anagrams generated 
# chest 
# chin 
# copper 
# copy 
# cry 
# he 
# history 
# hope 
# ... skip a few ... 
# theory 
# thin 
# this 
# tin 
# to 
# toe 
# top 
# yes 
 

2 comments:

  1. Would it be reasonable to write:

    def isAnagramOf(attempt, original):
        return (sorted(attempt.lower())
            == sorted(original.lower()))

    ReplyDelete
  2. @François I think your def would work well as long as the attempt is the same size as the original. Once the attempt is a subset of the original it no longer works.

    ReplyDelete