Scrabble_efficient_code


#1

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(x):
  j=0
  z=0
  for y in x:
    
    print (y)
    
    for key,value in score.items():
        
      if key in y:
        print (key,'=',value)
        j=j+value
        print (j)
      elif y in "ABCDEFGHIJKLMNOPQRSTUVWXYZ":
        y=y.lower()
        if key in y:
          print (key,'=',value)
          z=z+value
          print (z)
      j=j+z 
  return j
print (scrabble_score('DuNe'))

Hi !
I worked on the exercise and I am getting the desired output . Can anyone suggest how to further make my code more efficient? I know it can be done but how, is what I am not able to write..?


#2

For this exercise you can assume all inputs are valid

so you can just loop over x and then add score[x] to z


#3

I was able to do it a bit more efficiently I think.

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):
    l_word=word.lower()
    w_score =0
    for i in (l_word):
        l_score=score[i]
        w_score = w_score+l_score
    return w_score

#4

Is there anything wrong with hacking it down to:

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):
    word = word.lower()
    total = 0
    for i in (word):
        total += score[i]
    return total

I don't often see people in the forums using the "x += y" format


#5

its used quit a lot, but the people who come to the forum struggle a lot, so maybe they are less likely to use += shorthand? Can't verify its true, but its possible

but += is perfectly valid and good to use


#6

This was really helpful.


#7

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