三个参数的比较
我有一个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
这个函数在14个测试案例中,有12个都能正常工作 -
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
这到底是为什么呢?
2 个回答
0
def isValidWord(word, hand, wordList):
return word in wordList and all(hand.get(a, 0) >= b for a, b in getFrequencyDict(word).items())
试试这个,这样可以得到正确的结果。
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