Python 字典值

0 投票
4 回答
1262 浏览
提问于 2025-04-17 18:10

你好,我刚开始学习编程,现在需要在Python中写一个函数,下面是这个函数的思路:

这个函数会返回 True,如果 wordwordList 中,并且这个单词完全由手中的字母组成。否则,它会返回 False。这个函数不会改变手中的字母或单词列表。

我有一个函数可以检查用户输入的单词中字母的频率,并把它转换成一个字典。我尝试过用不同的方法来使用iteritems,但都没有成功。我在处理那些有重复字母的单词时遇到了麻烦,因为当我手中没有两个相同字母的情况下,它们却被错误地返回为true。

如果我说得不清楚,抱歉,我才刚开始学习两周。任何建议都非常欢迎,我在这个问题上卡了很久!

def isValidWord(hand,word,wordList):

    """
    Returns True if word is in the wordList and is entirely

    composed of letters in the hand. Otherwise, returns False.

    Does not mutate hand or wordList.

    word: string
    hand: dictionary (string -> int)
    wordList: list of lowercase strings
    """

    wordC = getFrequencyDict(word)
    handC = dict.copy(hand)
    if word not in wordList:
        return False
    for c in word:
        if c not in hand:
            return False
        for k,v in wordC.iteritems():
            if k in hand and v > 1:
                 handC[k] -= 1

基本上,我接下来的步骤是尝试找出如何将单词与手中的字母进行比较,并且要忽略任何值为零的字母。我觉得(希望)这样可以解决问题。

4 个回答

0

Python里的Counter类是个好帮手。你可以在Python 2.7及之后的版本中使用它:

from collections import Counter

def is_valid_word(hand, word, word_list):
    letter_leftover = Counter(hand)
    letter_leftover.subtract(Counter(word))
    return word in word_list and all(v >= 0 for v in letter_leftover.values())

接下来:

>>> def test():
...     hand = "traipse"
...     word_list = ["all", "the", "words", "in", "English", 
                     "parts", "pines", "partiers"]
...     print is_valid_word(hand, "parts", word_list)
...     print is_valid_word(hand, "pines", word_list)
...     print is_valid_word(hand, "partiers", word_list)
... 
>>> test()
True
False
False
1

你可以试试这样的写法:

def isValidWord(hand, word, word_list):
    if word not in word_list:
        return False
    for c in word:
        if c not in hand:
            return False
    return True

因为字符串是可以逐个字符遍历的,所以你可以一个一个地检查字符。

祝你好运!

1

在没有看到你的代码的情况下,我来看看我是否理解你的意思:你是想检查一个给定的单词是否可以用字母 hand 来拼写,就好像用户手里有每个字母的拼字游戏棋子,对吧?

我个人的做法是直接复制 hand 这个字典,然后对复制的内容进行修改。大概可以这样做:

def is_valid_word(hand, word, wordlist):
    hand_cp = dict(hand)
    for letter in word:
        if hand_cp.get(letter):
            # The letter is in our hand, so "use it up".
            hand_cp[letter] = hand_cp[letter] - 1
        else:
            # The letter isn't in our hand, so the word isn't valid.
            return False

    # If we can make the word, now make sure it's a real word:
    # (If wordlist is long, you might want to sort it and do a real search)
    if word not in wordlist: 
        return False

    # We haven't found any reason to return False, so this is a valid word.
    return True

撰写回答