-1

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

Max Kraus
  • 137
  • 3
  • 9
  • like in any order or in specific spots, ie car, rac = 3 as well? what about repeats – lPlant Dec 05 '17 at 16:43
  • Do you know how to [Iterate over a string in Python](https://stackoverflow.com/questions/43605490/python-iterate-over-string)? That will let you go character by character. – Davy M Dec 05 '17 at 16:44
  • Iterate though the first string, add 1 if you find the current character in the second string. Return result ? – IMCoins Dec 05 '17 at 16:44
  • @lPlant yes, car and rac should be 3 as well – Max Kraus Dec 05 '17 at 16:46
  • I could answer this question with "Yes I have a clue." But I don't think that's the answer you're looking for. Try to make sure your question is meaningful. – Davy M Dec 05 '17 at 16:46

3 Answers3

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

SuperStew
  • 2,857
  • 2
  • 15
  • 27
2

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})
Abhijith Asokan
  • 1,865
  • 10
  • 14
Patrick Haugh
  • 59,226
  • 13
  • 88
  • 96
1

Something like this

count = 0

for letter in set(string1):
  count += string2.count(letter)

print(count)
RoachLord
  • 993
  • 1
  • 14
  • 28