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 advance
Max
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 advance
Max
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
Here's a solution using Counter
. We make a Counter
for each of the words, then find the intersection of those Counter
s. 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})
Something like this
count = 0
for letter in set(string1):
count += string2.count(letter)
print(count)