我在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个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
现在为什么会这样?
答案 0 :(得分: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
答案 1 :(得分:0)
def isValidWord(word, hand, wordList):
return word in wordList and all(hand.get(a, 0) >= b for a, b in getFrequencyDict(word).items())
试试这会给出正确的答案