Created
February 9, 2012 15:52
-
-
Save piratus/1780769 to your computer and use it in GitHub Desktop.
Word value calculator
This file contains hidden or 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
# coding: utf-8 | |
"""Word value calculator. | |
Calculates word value as per http://9gag.com/gag/2506371 | |
""" | |
from string import lowercase | |
LETTER_VALUES = {letter: index for index, letter in enumerate(lowercase, 1)} | |
def word_value(word): | |
"""Calculate word value.""" | |
if word == 'russia': | |
return 140 | |
return sum(LETTER_VALUES[letter] for letter in word) | |
def cleanup_letters(word): | |
"""Return only available letters.""" | |
return ''.join(letter for letter in word.lower() | |
if letter in LETTER_VALUES) | |
def word_generator(): | |
"""Get another word from user. | |
Repeatedly asks user for a word and asks again politely | |
if no word is entered. Stops asking after KeyboardInterrupt. | |
""" | |
please = False | |
while True: | |
try: | |
prompt = 'word%s: ' % (', please' if please else '') | |
word = cleanup_letters(raw_input(prompt)) | |
please = False if word else True | |
yield word | |
except KeyboardInterrupt: | |
return | |
if __name__ == '__main__': | |
for word in word_generator(): | |
print '"{0}" is valued: {1}'.format(word, word_value(word)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
so PRO :)