Skip to content

Instantly share code, notes, and snippets.

@sirpengi
Forked from sixthgear/scrabble.py
Created December 7, 2011 05:28
Show Gist options
  • Save sirpengi/1441582 to your computer and use it in GitHub Desktop.
Save sirpengi/1441582 to your computer and use it in GitHub Desktop.
import string
import sys
class count_dict(dict):
"""
stub object used to simplify tracking
the number of letters encountered.
this expects to be initialized with an uppercase letter yo.
"""
def __init__(self, s=''):
super(dict, self).__init__()
self.wildcards = 0
for c in s:
if c == '?':
self.wildcards += 1
else:
self.incr(c)
def incr(self, c):
if c not in self:
self[c] = 0
self[c] += 1
def get_dictionary(fn):
"""
Return list of all words in CAPS.
"""
with open(fn) as fh:
for line in fh:
yield "".join(c for c in line.strip().upper() if c in string.ascii_uppercase)
def word_in_set(w, s):
cd = count_dict()
wildcards = s.wildcards
for c in w:
cd.incr(c)
if c not in s or cd[c] > s[c]:
wildcards -= 1
if wildcards < 0:
return False
return True
def find_words(fn, letters):
"""
For a given dictinary file, find the longest words that can be created from
the given set of letters.
"""
results = []
longest = 0
mycd = count_dict(letters.strip().upper())
for word in get_dictionary(fn):
if len(word) < longest:
continue
if word_in_set(word, mycd):
if len(word) > longest:
longest = len(word)
results = [word]
else:
results.append(word)
return results
if __name__ == '__main__':
if len(sys.argv) < 3:
print 'Usage: scrabble.py dictionary [letter... ]'
sys.exit()
for r in find_words(sys.argv[1], "".join(sys.argv[2:])):
print r
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment