Would this def work fine? (scrabble_score)


#1

I’m just a little bit confused because my def looks so different from the ‘get code’ def but it still passed. Do you think it works fine?

#GET_CODE DEF:

def scrabble_score(word):
  word = word.lower()
  total = 0
  for letter in word:
    for leter in score:
      if letter == leter:
        total = total + score[leter]
  return total


#MY DEF:

def scrabble_score(word):
  points = 0
  for char in word:
    points += score["%s" % (char.lower())]
    
  return points


#2

yes, both are fine :slight_smile:

you yourself can check this.just call your function with an argument.

print scrabble_score("something")

so you can choose whichever you like :slight_smile:


#3

What would happen if the character is not in the dictionary though? The original checks for that and mine doesn’t, right?


#4

Hi @megamaster83413,

Your are right that your code does not check whether or not the character is in the dictionary. If word includes a problematic character, it will raise a KeyError.

You could check for invalid characters as follows …

  for char in word:
    # add to points only if char is in score
    if char.lower() in score:
      points += score["%s" % (char.lower())]

With such checking, any invalid characters will be ignored.

It might be better to convert word to lowercase prior to the for loop or within the loop header. Then you would not need to convert individual characters within the loop.

You could also simplify this …

    points += score["%s" % (char.lower())]

The string formatting is not needed there.


#5

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