2016-08-09 72 views
1

我正在使用單詞中的字符來搜索字典的鍵。字典是SCRABBLE_LETTER_VALUES:{'a':1,'b':3,...}等等。使用可變鍵返回字典值

這裏是我的殘缺碼:

""" 
Just a test example 
word = 'pie' 
n = 3 
""" 

def get_word_score(word, n): 
""" 
Returns the score for a word. Assumes the word is a 
valid word. 

The score for a word is the sum of the points for letters 
in the word multiplied by the length of the word, plus 50 
points if all n letters are used on the first go. 

Letters are scored as in Scrabble; A is worth 1, B is 
worth 3, C is worth 3, D is worth 2, E is worth 1, and so on. 

word: string (lowercase letters) 
returns: int >= 0 
""" 
score = 0 
for c in word: 
    if SCRABBLE_LETTER_VALUES.has_key(c): 
    score += SCRABBLE_LETTER_VALUES.get("""value""") 

下面這段代碼是不完整的,因爲我還在學習蟒蛇,所以我仍然可以通過這個問題思考,但我被困在返回的方面值用一個改變每次迭代的鍵。

我雖然也許可以設置c等於它匹配的關鍵然後返回值,但我不知道該怎麼做。此外,我想檢查一下,看看我是否確實在正確的思維過程中,可以這麼說。

只是FYI這個代碼庫成功地進入循環,我根本無法檢索的價值。

感謝您的建議!

+0

你是在混合2個還是4個空格縮進? – Julien

+0

你是對的!我只是修正了這一點。謝謝 – Chris

+0

任何其他問題? – depperm

回答

2

你可以做到以下幾點:

score = 0 
for c in word: 
    score += SCRABBLE_LETTER_VALUES.get(c, 0) 
return score 

get()將返回如果字典包含它的鍵的值,否則將在片段返回作爲第二個參數(0傳遞的默認值)。

+0

感謝您的答案和建議清理代碼一點! – Chris

-1

您在每次迭代中都將score置零。您應該在for循環之前初始化它。

score = 0 
for c in word: 
    score += SCRABBLE_LETTER_VALUES.get(c, 0) 
return score 
相關問題