Skip to content

Instantly share code, notes, and snippets.

@chadselph
Created December 13, 2011 01:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chadselph/02de01a95d28913f69ac to your computer and use it in GitHub Desktop.
Save chadselph/02de01a95d28913f69ac to your computer and use it in GitHub Desktop.
def score_word_1():
score = 0
for letter in word.upper():
if letter in "AEILNORSTU":
score+=1
elif letter in "DG":
score+=2
elif letter in "BCMP":
score+=3
elif letter in "FHVWY":
score+=4
elif letter in "K":
score+=5
elif letter in "JX":
score+=8
elif letter in "QZ":
score+=10
return score
# or a slightly more "Pythonic" way would be
def score_word_2(word):
word_score = 0
groups = {"AEILNORSTU":1, "DG":2, "BCMP":3,
"FHVWY":4, "K":5, "JX": 8, "QZ":10}
for letter in word.upper():
for letters, letter_score in groups.items():
if letter in letters:
word_score += letter_score
break
return word_score
@reneighbor
Copy link

Sweet, "if letter in" is supremely useful, geez. I feel like people who learned programming on Java and then discover Python must feel like teenagers who leave home at age 18 and find out that everyone else's parents let them have dessert before dinner.

I guess "groups" is your hash then? I don't see when "letters" and "letter_score" are defined/initialized...maybe Python lets you do that eh? You do initialize word_score but not letter_score if I'm not mistaken.

@chadselph
Copy link
Author

letter_score actually comes from the for loop. groups.items() returns a list of tuples from the dictionary, in this case: [('FHVWY', 4), ('JX', 8), ('DG', 2), ('K', 5), ('QZ', 10), ('BCMP', 3), ('AEILNORSTU', 1)]. Line 27's for-loop is assigning letters and letter_score to each 2-tuple of the iteration of the list. It only works if every item in the list is an iterable of length 2.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment