Scrabble stone!


The code below works for the Scrabble stone (I found it on a post two years ago), however, I still wondered what's the "i"'s function in this code? the "i" in this line "for i,c in enumerate(lword):" without the i, the error message is "Your code looks a bit off--it threw a "(0, 't')" error."

score = {"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 scrabble_score(word):
    lword = word.lower()
    tscore = 0
    for i,c in enumerate(lword):
        tscore += score[c]
    return tscore

print scrabble_score("Zero")


It does not have any function which means that the wrong tool for the job has been employed. Sort of like hammering in a screw.

The table above is used for look-up purposes only, and we do not need to enumerate the word, only iterate over each letter in the word, and look up its score.

    for letter in word.lower():
        total += score(letter)
    return total

enumerate is a function that takes a list and enumerates it by adding an index. It returns an iterator made up of index/value pair tuples.

>>> list(enumerate('word'))
[(0, 'w'), (1, 'o'), (2, 'r'), (3, 'd')]

As we can see, i is the index, or first value in the tuple, and c is the text character, or second value of the tuple. A little more than we need in this instance, so overkill.


An interesting use of enumerate() would be if we wanted the index of the letter with the highest score in the word.

def score_and_highest(word): 
    highest = 0
    idx = 0
    total = 0
    for i, c in enumerate(word):
        value = score[c]
        if value > highest:
            highest = value
            idx = i
        total += value
    return word, total, word[idx], highest

_word = 'cyclopse'
print ("Word: %s\nWord score: %d\n\
Highest letter score: %s => %d " % score_and_highest(_word))

Word: cyclopse
Word score: 17
Highest letter score: y => 4

The above assumes at least one of the letters is already on the board since there are only seven letters in the tray for any one turn.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.