【问题标题】:Checking if a value appears in both a string and a dictionary检查一个值是否同时出现在字符串和字典中
【发布时间】:2017-11-12 20:45:02
【问题描述】:

作为一个更大问题的一部分,我必须编写一个函数来检查给定 word 中的所有字母是否出现在名为 hand 的字典中(以及在一个单词列表中,但我在这里省略了那部分),并确保如果一个字母出现两次,例如,在单词中,它必须在字典中出现至少同样多次。这是我编写的函数之一:

def is_valid_word(word, hand):
    for let in word:
        if let in hand.keys():
            if hand[let]>=word.count(let):
                return True
            else:
                return False

我也试过这种方式:

def is_valid_word(word, hand):
    for let in word:
        if let not in hand.keys():
            return False
        else:                                 #in another variation I merged 
            if hand[let]>=word.count(let):    # these two lines with _elif_
                return True
            else:
                return False

在其他类似的函数中我没有专门写hand.keys(),只是用了

if let in/not in hand 

仍然每次我尝试使用

的功能
print is_valid_word("account", {"a":1, "c":1, "l":2, "n":1, "o":3, "r":2, "t":1, "y":1})

即使字母“c”在单词中出现两次但在字典中只出现一次,它也会返回 True(我也尝试使用不同措辞的字典来使用“破裂”这个词,但我在这里给出的第二个例子涉及它是它应该的方式,不像其他人)。 有什么想法吗?

编辑:这是问题中的解释方式,希望它更容易理解:

“一个有效的单词在单词列表中;它完全由当前手牌的字母组成。 实现 is_valid_word 函数。

def is_valid_word(word, hand, word_list):
"""Returns True if word is in the word_list and is entirely 
composed of letters in the hand. Otherwise, returns False.
Does not mutate hand or word_list.
word: string
hand: dictionary (string -> int)
word_list: list (string)
"""
# TO DO ... "

【问题讨论】:

    标签: python string dictionary key


    【解决方案1】:

    我会使用allcollections.Counter 使其直截了当。

    >>> def is_valid_word(word, hand, word_list):
    ...     if word in word_list:
    ...         return all(letter_dict[letter] >= hand[letter] for letter in Counter(word) if letter in hand ) 
    >>>     return False
    

    【讨论】:

    • 还没有研究过这些概念,但会马上检查出来。谢谢!
    【解决方案2】:

    如果我没有误会你想检查一个单词的所有字母是否都是dict的key,并且dict中的相关值大于单词中字母的出现次数。不幸的是,您的程序有一个明显的错误。只有在检查第一个字母后才会终止循环。

    修改后应该是这样的:

    def is_valid_word(word, hand):
        for let in word:
            if let in hand and hand[let]>=word.count(let):
                continue
            else:
                return False
        return True
    

    希望对你有帮助。

    【讨论】:

      【解决方案3】:

      函数返回单词中第一个字母的结果——终止函数。 for 循环不会超过第一个字母。

      修改函数,使其仅在所有字母有效时返回True。 (在第一个无效字母上仍然返回False 是可以的。)

      【讨论】:

      • 问题不在于循环机制;问题是你总是return Truereturn False 在检查 first 字母后终止函数。
      • 明白了。看看我能做什么
      猜你喜欢
      • 1970-01-01
      • 2022-12-14
      • 1970-01-01
      • 1970-01-01
      • 2010-10-05
      • 2014-09-16
      • 1970-01-01
      • 2022-11-02
      相关资源
      最近更新 更多