Sunday, November 26, 2006

python jumble solver

over thanksgiving, i figured it'd be a good hack to solve the jumble . Originally, i tried to do all permutation of letter orders in the word but got confused and just did letter frequency:

import sys

word = len(sys.argv) > 1 and (sys.argv[1]).strip("\n").lower() or "egaugnal"
words = [w.strip("\n").lower() for w in open('/usr/share/dict/web2') if len(w) == len(word)+1]

def lfreq(w):
wfreq = {}
for letter in w: wfreq[letter] = letter in wfreq and wfreq[letter]+1 or 1
return wfreq

wfreq = lfreq(word)
match = [w for w in words if lfreq(w) == wfreq]

print match

that will print all matches for the word send in on the command line, assuming your dictionary file is in /usr/share/dict/web2 :-( . I tried for a while to do a recursive permute function which would take a word or list of letters and return all possible permutations: permute('abc') -> ['abc','acb','bca',bac',cba',cab'], which would clearly be a faster solution. but, as mentioned, i got confused and lazy. and the script above runs in <>