0

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

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

它总是返回假我怎样才能让它返回真?!?请帮忙!!!

因此,如果

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})

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

4

2 回答 2

1

您可以简单地使用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/

于 2013-03-09T20:03:37.050 回答
0

这应该有效:

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
于 2013-03-09T20:01:28.133 回答