Pondering 42 in Finite States

Yet another blog, by yet another person.

Random stuff about Python, Java, Scala, and other random stuff.

2010-07-11

Re-inventing the Wheel, Poorly: Finding Words Made from Given Letters Using a Word List

Yet another case of re-inventing the wheel, poorly.

This is a small script to find words that are longer than a supposed longest word that can be made from a set of letters (letters in the set may be repeated):

#!/usr/bin/env python3
from contextlib import contextmanager

@contextmanager
def words_made_from(letters):
    letters = frozenset(letters)
    words_file = open('/usr/share/dict/words')
    words = (line.rstrip() for line in words_file)
    yield (word for word in words if frozenset(word) < letters)
    if words_file is not None:
        words_file.close()

if __name__ == "__main__":
    from sys import argv
    if len(argv) == 3:
        letters, longest = argv[1:3]
        supposed_longest = len(longest)
        with words_made_from(letters) as words:
            for word in words:
                if len(word) > supposed_longest:
                    print(word)
    else:
        print("Usage: finder.py letters supposed-longest-word")

This came out of the need to verify the claim that the words "typewriter" and "stewardesses" were the longest words that can be typed with one row and left hand letters on a typical keyboard with QWERTY layout.

If we leave out the last letter in the supposed longest word, it will list words with the same length. Here is the example for the first claim.

..@....:~/devel/py$ ./finder.py 'qwertyuiop' 'typewriter'
..@....:~/devel/py$ ./finder.py 'qwertyuiop' 'typewrite'
perpetuity
proprietor
repertoire
typewriter

Since this is just a throwaway script and not a long-running program, I could have just used this (and using Perl, it could even have been compressed into a one-liner with a just a dozen characters or so :-) ):

from sys import argv
lng, ls = len(argv[1]), set(argv[2])
for word in (w for w in map(str.rstrip, open('/usr/share/dict/words'))
        if set(w) < ls and len(l) > lng):
    print(word)

But, to abuse a quote attributed to Blaise Pascal:

I would have written a shorter letter, but I did not have the time.

This page is powered by Blogger. Isn't yours?

Feeds

Subscribe to
Posts [Atom]

Bookmarks

Previous Posts

Archives

   2004-05     2004-06     2004-11     2005-04     2005-05     2005-06     2005-10     2006-10     2007-02     2007-03     2007-04     2007-12     2008-03     2008-06     2008-07     2008-09     2008-10     2009-07     2010-07 
© 2004-2009 FiniteState42i (yahoo.com ID: finitestate42i)