Skip to content

Instantly share code, notes, and snippets.

@flniu
Last active June 29, 2017 15:28
Show Gist options
  • Save flniu/2545613476bb81cb7f3a4a9728bb15f5 to your computer and use it in GitHub Desktop.
Save flniu/2545613476bb81cb7f3a4a9728bb15f5 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import argparse
import collections
scores = {"a": 1, "c": 3, "b": 3, "e": 1, "d": 2, "g": 2,
"f": 4, "i": 1, "h": 4, "k": 5, "j": 8, "m": 3,
"l": 1, "o": 1, "n": 1, "q": 10, "p": 3, "s": 1,
"r": 1, "u": 1, "t": 1, "w": 4, "v": 4, "y": 4,
"x": 8, "z": 10}
def get_word_letter_counter(word):
""" return a dict of { letter: count } """
return collections.Counter(word.lower())
def get_word_list_from_file(filename):
""" return an iterator of (word, word_letter_counter) tuple """
for line in open(filename):
word = line.rstrip('\n')
yield (word, get_word_letter_counter(word))
def get_rack_from_arg():
""" return a string of rack """
parser = argparse.ArgumentParser(description='Scrabble cheater')
parser.add_argument('rack', help='input a rack')
args = parser.parse_args()
return args.rack
def get_word_score(word_letter_counter):
""" return an integer of word score """
return sum(scores[letter] * count for letter, count in word_letter_counter.items())
if __name__ == '__main__':
rack = get_rack_from_arg()
rack_letter_counter = get_word_letter_counter(rack)
def is_valid_word(word_letter_counter):
return all(count <= rack_letter_counter.get(letter, 0)
for letter, count in word_letter_counter.items())
valid_words = (
(get_word_score(word_letter_counter), word)
for word, word_letter_counter in get_word_list_from_file('sowpods.txt')
if is_valid_word(word_letter_counter)
)
for score, word in sorted(valid_words, reverse=True):
print(score, word)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment