【问题标题】:boolean loopd keys strings comparator布尔循环键字符串比较器
【发布时间】:2013-02-25 05:58:53
【问题描述】:

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

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

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

如果

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})应该返回假而不是真!

【问题讨论】:

    标签: python string loops frequency


    【解决方案1】:

    这应该可行:

    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
    

    【讨论】:

    • 为什么在这种情况下不起作用 - >>> plum = "plum" >>> pluma = {'f': 1, 'h': 1, 'k': 1 , 'm': 1, 'l': 1, 'p': 1, 'u': 1, 'y': 1} >>> print compareTo(plum, pluma) False
    • 什么情况下不起作用?我得到的输出是 cmets ...
    • @user2152315 要使其适用于您的情况,您需要应用上述评论中的更改
    • 在 "plum" 和 {'f': 1, 'h': 1, 'k': 1, 'm': 1, 'l': 1, 'p' 的情况下: 1, 'u': 1, 'y': 1} 它应该返回True时返回False
    • @user2152315 我建议更改问题描述以加强那些 hand 字典中的数字是下限 - 不相等的值
    【解决方案2】:

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

    【讨论】:

    • 不错。我会添加 Counter 自 2.7 以来在 Python 中的信息。在某些情况下,这可能会破坏交易...
    猜你喜欢
    • 2015-02-24
    • 1970-01-01
    • 2017-08-13
    • 2011-08-21
    • 1970-01-01
    • 2021-11-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多