Common letters in two lines

I am trying to solve this program that takes two lines as input and prints the number of common letters. For example, if the input was "common" and "connor", then the output should be 4 (1 c, 1 n and 2 o). I used the set () function, but it outputs 3 (it treats both o as a single generic letter). Any help would be appreciated. Thank!!!

Btw here is the code I wrote:

print("Enter number of inputs: ")
c = int(input())
store = []
for each_item in range(c):
    print("Enter First String: ")
    one = input()
    print("Enter Second String")
    two = input()
    s = len(set(one) & set(two))
    store.append(s)
for each_number in store:
    print(each_number)
+3
source share
2 answers

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
+7
source

you can do this for this list

>>> 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 ok now

0
source

All Articles