2013-06-23 66 views
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(word): 
    count=0 
    word.lower() 
    print word 
    for char in word: 
     count=count+score[char] 
    return count 

我基本上需要輸入單詞並根據字典計算其分數。此代碼段不適用於大寫字母和小寫字母

+0

您可以更容易地完成循環:'count = sum(字中char的分數[char])'。 –

+1

請注意,您可以將'scrabble_score(word)'表示爲'sum(char [char] for word.lower())' – Eric

+0

重複[爲什麼不調用Python字符串方法除非將其賦值輸出?](http://stackoverflow.com/questions/9189172/why-doesnt-calling-a-python-string-method-do-anything-unless-you-assign-its-out) – smci

回答

8

這個修改後的代碼將工作:

def scrabble_score(word): 
    count=0 
    word = word.lower() #assign the result of word.lower() to word 

word.lower()返回修改後的話,它不會修改字符串就地。在Python中,字符串是不可變。這.lower()返回一個字符串的事實被定義爲這樣的:

>>> help(str.lower) 
Help on method_descriptor: 

lower(...) 
    S.lower() -> string 

    Return a copy of the string S converted to lowercase. 
5

str.lower()返回字符串的一個副本 - 它不會改變原始字符串。嘗試:

word = word.lower() 
4

scrabble_score函數可以更簡單地表達這樣的:

def scrabble_score(word): 
    return sum(score[char] for char in word.lower()) 

在Python,表達一個迭代中的慣用的方式是使用生成器表達式(如在上面的代碼)或列表解析。

關於您當前的問題,正如其他答案中指出的那樣,lower()方法(以及所有其他字符串方法)不會修改字符串,因此您必須重新分配返回的值,或者立即使用它,如我的答案所示。

+1

+1更好的版本OP的代碼 – HennyH

相關問題