2013-03-09 47 views
0

我有Python中的函數,它說我得把3個參數和字必須是在手,這個詞也必須在單詞表比較三者之間

def isValidWord(word, hand, wordList): 
    d = hand.copy() 
    for c in word: 
     d[c] = d.get(c, 0) - 1 
     if d[c] < 0 or word not in wordList: 
      return False 
    return sum(d.itervalues()) == 0 

它完美在12 outta 14測試案例 -

Function call: isValidWord(hammer, {'a': 1, 'h': 1, 'r': 1, 'm': 2, 'e': 1}, <edX internal wordList>) 

Output: 
True 

但在其他情況下,它錯了!

Random Test 1 
Function call: isValidWord(shrimp, {'e': 1, 'i': 1, 'h': 1, 'm': 1, 'l': 1, 'n': 1, 'p': 1, 's': 1, 'r': 1, 'y': 1}, <edX internal wordList>) 
Your output: 
False 
Correct output: 
True 

Random Test 5 
Function call: isValidWord(carrot, {'a': 1, 'c': 1, 'l': 2, 'o': 1, 's': 1, 'r': 2, 't': 1, 'x': 1}, <edX internal wordList>) 
Your output: 
False 
Correct output: 
True 

Random Test 7 
Function call: isValidWord(shoe, {'e': 1, 'd': 1, 'h': 1, 'o': 1, 's': 1, 'w': 1, 'y': 2}, <edX internal wordList>) 
Your output: 
False 
Correct output: 
True 

現在這是爲什麼?

回答

1

您的功能是排除包含單詞字母多餘字母的「手」。例如,f('tree', {'t': 1, 'r': 1, 'e': 2, 's': 1})'trees')應返回True,因爲該「手」包含製作'tree'所需的所有字母。

你並不需要檢查他們:

def isValidWord(word, hand, wordlist): 
    if word not in wordlist: 
     return False 

    for letter in word: 
     if letter not in hand: 
      return False 

     hand[letter] -= 1 

     if hand[letter] < 0: 
      return False 

    return True 
+0

日Thnx一百萬AMIGO ...我得到它現在! – user2152315 2013-03-09 21:50:49

0
def isValidWord(word, hand, wordList): 
    return word in wordList and all(hand.get(a, 0) >= b for a, b in getFrequencyDict(word).items()) 

試試這個它會給出正確的響應