Skip to content Skip to sidebar Skip to footer

Python Compare Two Strings And Check How Many Chars They Have In Common

I'm just wondering how I can check how many chars two string have in common. For example if I have 'car' and 'cars', the result should be 3. Anybody a clue? Cheers and thanks in a

Solution 1:

Here's a solution using Counter. We make a Counter for each of the words, then find the intersection of those Counters. That itself is a Counter, and we can just sum the values to find the number of shared characters

from collections import Counter

def shared_chars(s1, s2):
    return sum((Counter(s1) & Counter(s2)).values())

print(shared_chars('car', 'carts'))

will print

3

In case of Counter, intersection is the minimum of corresponding counts.

>>> Counter('abbb') & Counter('bcc')
Counter({'b': 1})

Solution 2:

Since you didn't write any code, I won't either. But basically this:

-convert strings to list

-use set to get letters they have in common

-get length of your set

Biggest hazard here would be if you wanted to count repeating letters

Solution 3:

Something like this

count = 0

for letter inset(string1):
  count += string2.count(letter)

print(count)

Post a Comment for "Python Compare Two Strings And Check How Many Chars They Have In Common"