Archives for 13 Dec,2009

You are browsing the site archives by date.

Python: Wordwheel / WordCube solver

Often in newspapers there is a wordwheel or some variant, whereby you have to find as many words greater than 3 letters long, containing the centre word and using the letters no more than once. I have created a webpage that generates a “WordCube” daily for people to peruse at their leisure (www.stealthcopter.com/wordcube). This post contains the code and explanation of the solutions to wordcube’s (and all other word<insert shape here>).

WordCube from http://www.stealthcopter.com/wordcube for 12/12/2009
Example WordCube image for the 12th December 2009 from www.stealthcopter.com/wordcube/2009/12/12

Below is a function I wrote to check if an input was a valid anagram (or partial anagram, as it isn’t essential to use every letter). The function works by cycling over each letter of word we are testing (word), and checks if the letter is valid (checked against chkword). If the letter is valid then it removes the letter from the original word and moves to the next letter until we run out of letters (returns True) or if the letter is invalid (returns False).

def anagramchk(word,chkword):
	for letter in word:
		if letter in chkword:
			chkword=chkword.replace(letter, '', 1)
		else:
			return False
	return True

f=open('english', 'r')
word=raw_input('Input letters (starting with mandatory letter) :')
minlen=4
count=0
for l in f:
	l=l.strip()
	if len(l)<=len(word) and len(l)>=minlen and word[0] in l and anagramchk(l,word):
		if len(l)==len(word):
			print l,'  <-- Long word'
		else:
			print l
		count+=1
f.close()
print count

This will output a list of the possible words, along with a total. The results can be seen for the WordCube in the example above here (To prevent spoiling it if you’d like to have a go at it yourself).

As always I’d be interested to see if anyone knows any faster methods or any other general improvements or comments.

The dictionary file can be found here (not perfect):
here

Read More