Faster way to do this?
Skip Montanaro
skip at pobox.com
Wed May 21 02:16:26 EDT 2003
Freddie> I'm not sure what it's called. You're given a set of letters
Freddie> ('olhel', for example), and you're supposed to come up with a
Freddie> bunch of words that use only those letters. In this case, it
Freddie> might be ('he', 'hell', 'hello', 'hoe', 'hole', 'oh').
Boggle?
My version is appended to this note. Here's the output on my machine for
your version and mine:
% python findwords-orig.py hello
Read 234937 words in 1.12s
Method 1: found 17 words in 6.39s
% python findwords.py hello
loaded 234937 words into dictionary in 1.11 seconds
found 17 words in 0.00 seconds
Skip
import sys
import time
WORD_FILE = "/usr/share/dict/words"
start = time.time()
dictionary = {}
wf = open(WORD_FILE, 'r')
for line in wf:
dictionary[line.strip()] = True
print "loaded %d words into dictionary in %.2f seconds" % (len(dictionary),
time.time()-start)
def findwords(dictionary, letters, prefix="", seen={}):
for i in range(len(letters)):
newprefix = prefix+letters[i]
if newprefix in dictionary and newprefix not in seen:
print newprefix
seen[newprefix] = True
findwords(dictionary, letters[0:i]+letters[i+1:], newprefix, seen)
if __name__ == "__main__":
start = time.time()
findwords(dictionary, sys.argv[1].lower())
print "found matches in %.2f seconds" % (time.time()-start)
More information about the Python-list
mailing list