-
-
Save elirousso/4003160 to your computer and use it in GitHub Desktop.
Python helps you play Letterpress
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
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_WEIGHT * 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
Noticed WHITE_WEIGHT on line 38 was misspelled ;)