Monday, April 28, 2008

word riddle

This was in SciAm:Mind, which 'Brozy grabbed for me the other day.

In the word gum, every letter can be replaced by y to form a valid word, as follows:

gum
yum
gym
guy
There are about forty such three-letter words, but a script I threw together only finds seven such four-letter words: two with e, two with l, one with o, and two with r. Can you find them?

My solution script follows. Remove the pound signs for the answers. (Download the /usr/share/dict/words I used.)

#! /usr/bin/env python

testlen = 4
dict = {}
f = open('/usr/share/dict/words', 'r')
for line in f:
line = line.strip().lower()
if len(line) == testlen:
dict[line] = 1

chars = {}
for i in range(97, 123):
chars[chr(i)] = 0

for word, v in dict.iteritems():
for c, found in chars.iteritems():
found = 1
for j in range(testlen):
mod = word[:j]+c+word[j+1:]
if mod not in dict:
found = 0
break
chars[c] += found
#if found:
# print word+': '+c

print chars
Addendum: the o solution and one of the r solutions require proper nouns. Also, the o already has an o.

0 comments: