Faster way to do this?
Freddie
oinkfreddie at oinkmadcowdisease.oinkorg
Wed May 21 01:14:17 EDT 2003
Hi.
I was quite bored today, so I hacked up a quick Python script to do.. well,
I'm not sure what it's called. You're given a set of letters ('olhel', for
example), and you're supposed to come up with a bunch of words that use only
those letters. In this case, it might be ('he', 'hell', 'hello', 'hoe',
'hole', 'oh'). Just wondering if there's any way to make it faster, perhaps
using a bizarre list comprehension :)
Output on my K6/2 450 running Debian Linux, roughly average after 3 tries:
python2.1 wordfinder.py hello
Read 45392 words in 0.94s
Method 1: found 6 words in 4.49s
python2.2 wordfinder.py hello
Read 45392 words in 1.00s
Method 1: found 6 words in 3.71s
Freddie
BEGIN CODE
----------
import sys
import time
WORD_FILE = '/usr/share/dict/american-english'
def main():
if len(sys.argv) != 2:
print 'USAGE: wordfinder.py <letters>'
sys.exit(-1)
# Split the word into chars?
chars = [char for char in sys.argv[1].lower()]
# Read in the word file
start = time.time()
words = []
wf = open(WORD_FILE, 'ra')
for line in wf.xreadlines():
if line.endswith('\n'):
line = line[:-1]
words.append(line)
print 'Read %d words in %.2fs' % (len(words), time.time() - start)
# Try first method!
start = time.time()
found = method1(chars, words)
print 'Method 1: found %d words in %.2fs' % (found, time.time() - start)
def method1(chars, words):
found = 0
for word in words:
letters = [char for char in word]
for char in chars:
if char in letters:
letters.remove(char)
if not letters:
break
if not letters:
found += 1
return found
if __name__ == '__main__':
main()
--------------------------------------------------------------
Remove the oinks to see the light
More information about the Python-list
mailing list