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 <>

Saturday, November 18, 2006

simple AJAX

this is the AJAX implementation i use:

function jfetch(url,t,o) {
var req = jfetch.xhr();
req.open("GET",url,true);
req.onreadystatechange = function() {
if(req.readyState == 4){
var rsp = req.responseText;
if(t.constructor == Function) return t.apply(o,[rsp]);
t = document.getElementById(t);
t[t.value ==undefined ? 'innerHTML': 'value'] = rsp;
req = null;
}
};
req.send(null);
}
jfetch.xhr =
(window.ActiveXObject)
? function(){ return new ActiveXObject("Microsoft.XMLHTTP"); }
: function(){ return new XMLHttpRequest()};
it's short, it only checks for the transport (ActiveX or XHR) once, and it takes either an element id or a call back function. and, i can understand it.