【发布时间】: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