it.gen.nz

Writings on technology and society from Wellington, New Zealand

Sunday, October 26, 2008

Target puzzle solver

#
# Python program to solve target word puzzle.
# detail comments are in accompanying blog post.
#
import sys

# calculate the 'signature' of a string
# signature is a 26 long integer array counting the number of each letter

def sig(w):
	l = list(w)
	lettercount = range(26)
	for i in range(26):
		lettercount[i]=l.count(alpha[i])
	return lettercount	

# get a subset of the system dictionary, lower case, no newlines,
# no words to short or too long, and must have the target letter

def get_wordlist(letter):
	wl = open('/usr/share/dict/web2','r').readlines()
	return [w.strip('\n') for w in wl if (len(w)>4) and (len(w)<11) and 0<w.count(letter) and w.lower()==w]

# core of the program - get list of candidate words from dictionary.
# compare signatures of candidate words with signature of target string
# and format result

def check_target(letters):
	if len(letters)<>9:
		return 'Argument should be exactly nine letters'
	wordlist = get_wordlist(letters[4])
	tarsig = sig(letters)
	result = [w for w in wordlist if sigin(sig(w),tarsig)]
	result = [(len(w)==9) and w.upper() or w for w in result]
	return  reduce(lambda x,y:x+" "+y,result)

# compare signatures of words to see if one could be made from the other

def sigin(small,large):
	return min(map(lambda x,y:x<=y,small,large))

# Main part of program - everything above is functions.
# Call "check_target" on the argument if there is one otherwise ask user

alpha='abcdefghijklmnopqrstuvwxyz'

if len(sys.argv)>1:
        print check_target(sys.argv[1])
else:
        print check_target(raw_input())
posted by colin at 7:02 pm  

1 Comment

  1. […] the program is surprisingly concise. I’ve put the whole listing of it online, but here I’ll step through it to show how it […]

    Pingback by it.gen.nz » Hitting the target — 26 October 2008 @ 9:19 pm

RSS feed for comments on this post. TrackBack URI

Sorry, the comment form is closed at this time.

Powered by WordPress