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

现在这是为什么?

4

2 回答 2

1

您的功能不包括包含单词字母额外字母的“手”。例如,f('tree', {'t': 1, 'r': 1, 'e': 2, 's': 1})( 'trees') 应该返回True,因为“手”包含所有必要的字母 make '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
于 2013-03-09T21:38:11.380 回答
0
def isValidWord(word, hand, wordList):
    return word in wordList and all(hand.get(a, 0) >= b for a, b in getFrequencyDict(word).items())

试试这个,它会给出正确的回应

于 2014-03-19T19:42:58.257 回答