布尔循环键字符串比较器



我正在做一个python项目,我想将字符串与键和值列表进行比较-如果所有键都与单词字符串匹配一定次数,它应该返回True例如-def compareTo(word, hand):

   kal = False 
   for d in wordlists: 
       if d in word: 
          kal = True 
   return kal

它总是返回false,我怎么能使它返回true?!?请帮助! !

so if

word = "hammer"

hand =  {'a': 1, 'h': 1, 'r': 1, 'm': 2, 'e': 1}

值表示每个字母出现的频率如果我插入的参数为真,我怎么能使它返回真而不是假…

comapreTo("hammer",{'a': 1, 'h': 1, 'r': 1, 'm': 2, 'e': 1})

应该返回True而不是False, comapreTo("hammers",{'a': 1, 'h': 1, 'r': 1, 'd': 2, 'e': 1})应该返回False而不是True !

您可以简单地使用Counter来计数字母频率:

from collections import Counter
def compareTo(word, hand):
    return Counter(word) == hand

例如,Counter("hammer")Counter({'m': 2, 'a': 1, 'h': 1, 'r': 1, 'e': 1});由于Counter是类字典的,因此比较结果等于{'a': 1, 'h': 1, 'r': 1, 'm': 2, 'e': 1}

Counter是Python 2.7和Python 3.x内置的。如果您需要在Python 2.6或更早版本中使用它,可以从这里获取:http://code.activestate.com/recipes/576611/.

应该可以:

def compareTo(word, hand):
    d = hand.copy()
    for c in word:
        d[c] = d.get(c, 0) - 1
        if d[c] < 0:
            return False
    return True
word = "hammer"
hand =  {'a': 1, 'h': 1, 'r': 1, 'm': 2, 'e': 1}
print compareTo(word, hand)  # => True    
print compareTo("hammers", hand)  # => False
print compareTo("plum", {'f': 1, 'h': 1, 'k': 1, 'm': 1, 'l': 1, 'p': 1, 'u': 1, 'y': 1})  # => True

最新更新