Count Common Characters in Strings Python

Viewed 11666

The output of this code continues to be 4. However, the output should be 3. The set intersection is present because I believe that is the key towards the answer. The reasoning for the answer being 4 instead of 3 comes from the number of 2 qs and 1 r that match s2 in s1.

s2 = "qsrqq"
s1 = "qqtrr"
counts1=0
counts2=0
letters= set.intersection(set(s1), set(s2))
for letter1 in set(s1):
    counts1 += s2.count(letter1)
for letter2 in set(s2):
    counts2 += s1.count(letter2)


counts = min(counts1, counts2)
print (counts)

Any help is much appreciated.

9 Answers
def commonCharacterCount(s1, s2):
    return sum( min(s1.count(char), s2.count(char)) for char in (set(s1) & set(s2)))
def commonCharacterCount(s1, s2):
    s=0
    for i in list(set(s1)):
        count1=0
        count2=0
        if i in s2:
            count1 = s1.count(i)
            count2=  s2.count(i)
            s=s+min(count1,count2)

    return(s)

Another way, though very late...

def commonCharacterCount(s1, s2):
    
    count = 0
    
    for i in range(len(s1)):
        for j in range(len(s2)):
            if(s1[i]==s2[j]):
                count +=1
                s2 = s2.replace(s2[j],"",1)
                break
    return count
Related