Skip to content

Instantly share code, notes, and snippets.

@mstepniowski
Created October 28, 2012 10:34
Show Gist options
  • Save mstepniowski/3968275 to your computer and use it in GitHub Desktop.
Save mstepniowski/3968275 to your computer and use it in GitHub Desktop.
Python helps you play Letterpress
"""
Python helps you play `Letterpress <http://www.atebits.com/letterpress/>`_.
Requires `NLTK library <http://nltk.org/>`_ and cmudict corpus.
You can install the latter by executing the following two lines in Python shell:
>>> import nltk
>>> nltk.download()
I'd consider it cheating, though!
"""
import re
from collections import Counter
from nltk.corpus import cmudict
WORDS = [(word.lower(), Counter(word.lower()))
for word in cmudict.words()
if len(word) >= 3 and re.match('^[a-zA-Z]+$', word)]
# Weight of a white (neutral) letter
WHITE_WEIGHT = 1.0
# Weight of a light red (opposing player) letter
RED_WEIGHT = 1.9
# Blue (your) and dark red (protected) fields have weight 0
def hint(red, white, other):
"""Given light red, white and other letters on a board as strings,
returns five words giving the most points."""
target_red = Counter(red)
target_white = Counter(white)
target_all = Counter(red + white + other)
def fit(word):
result = 0
for letter, count in word[1].items():
target_all_count = target_all[letter]
if count > target_all_count:
return -1
result += WHITE_WEIHT * min(target_white[letter], count)
result += RED_WEIGHT * min(target_red[letter], count)
return result
return sorted(WORDS, key=fit, reverse=True)[:5]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment