common letters in two strings

前端 未结 2 823
小蘑菇
小蘑菇 2021-01-06 07:21

I\'ve been trying to solve this program which takes two strings as input and outputs number of common letters. For Example, if the input was \"common\" and \"connor\" then t

相关标签:
2条回答
  • 2021-01-06 07:47

    Use collections.Counter:

    >>> from collections import Counter
    
    >>> Counter('common')
    Counter({'m': 2, 'o': 2, 'c': 1, 'n': 1})
    >>> Counter('connor')
    Counter({'o': 2, 'n': 2, 'c': 1, 'r': 1})
    
    >>> common = Counter('common') & Counter('connor') # intersection
    >>> common
    Counter({'o': 2, 'c': 1, 'n': 1})
    >>> sum(common.values())
    4
    
    0 讨论(0)
  • 2021-01-06 07:58

    you can do list comprehension for that too

    >>> a = 'common'
    >>> b = 'connor'
    >>> sum([1 for l in a if l in b])
    4
    

    EDIT

    a,b = 'come','common'
    
    def collision_count(a,b):
        da = {l:a.count(l) for l in a}
        db = {l:b.count(l) for l in b}
        return sum(min(v,db[k]) for k,v in da.items() if k in db.keys())
    
    print collision_count(a,b)
    3
    

    Are you now ok with that?

    0 讨论(0)
提交回复
热议问题