Count number of common letters in two words in python

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.

asked May 30, 2017 at 18:28

Count number of common letters in two words in python

Drew BennettDrew Bennett

4833 gold badges6 silver badges25 bronze badges

7

If you want to maintain a count of the number of characters in common, you should use collections.Counter instead of set.

from collections import Counter

s2 = 'qsrqq' 
s1 = 'qqtrr'

common_letters = Counter(s1) & Counter(s2)  # => {'q': 2, 'r': 1}
print(sum(common_letters.values()))         # => 3

answered May 30, 2017 at 18:39

Count number of common letters in two words in python

lazy doglazy dog

2,29612 silver badges21 bronze badges

1

Here is a solution that doesn't involve sets:

s2 = sorted("qsrqq")
s1 = sorted("qqtrr")

count = 0
while len(s1)>0 and len(s2)>0:
    if s1[0] == s2[0]:
        count += 1
        s1 = s1[1:]
        s2 = s2[1:]
    elif s1[0] < s2[0]:
        s1 = s1[1:]
    else:
        s2 = s2[1:]

print(count)

answered May 30, 2017 at 18:41

Count number of common letters in two words in python

Scott HunterScott Hunter

47.5k11 gold badges56 silver badges95 bronze badges

1

#!/usr/bin/python
s2 = "qsrqq"
s1 = "qqtrr"
counts1=0
counts2=0
letters= set.intersection(set(s1), set(s2))
print ("letters: "+str(letters) + " intersection count: "+str(len(letters)))
for letter1 in set(s1):
    print ("letter1 " + str(letter1))
    counts1 += 1
for letter2 in set(s2):
    print ("letter2 " + str(letter2) )
    counts2 += 1

print ("counts1 " + str(counts1) + " counts2 " + str(counts2) )
counts = min(counts1, counts2)
print (counts)

This results in;

[~]$ python /tmp/test.py
letters: set(
['q', 'r']) intersection count: 2
letter1 q
letter1 r
letter1 t
letter2 q
letter2 s
letter2 r
counts1 3 counts2 3
3

Analysis, 2 is the correct answer (q and r are the only letters common to both), 3 is the lower number of either sets unique values.

answered May 30, 2017 at 18:48

Count number of common letters in two words in python

1

def commonCharacterCount(s1, s2):
    return sum( min(s1.count(char), s2.count(char)) for char in (set(s1) & set(s2)))

answered Dec 24, 2020 at 11:13

Count number of common letters in two words in python

1

I replaced your original chunk of code

for letter1 in set(s1):
    counts1 += s2.count(letter1)

to:

for letter1 in set(s1):
    v = s2.count(letter1)
    print("{0}:{1}".format(letter1, v))
    counts1 += v

It outputs, it is the letter with occurrence counts:

r:1
q:3
t:0

It is correct, string s2 is qsrqq and you check set(s1) which is set contains r and q The counts are correct. Similarly, If check the 2nd for-loop, the outputs are:

q:3
r:1
s:1

therefore the minimum count is 4.

answered May 30, 2017 at 18:36

Count number of common letters in two words in python

Haifeng ZhangHaifeng Zhang

28.3k19 gold badges72 silver badges119 bronze badges

Do a count for each letter, and take the minimum to find out how many of that letter are common to both strings. Then sum that up, and that's your answer.

for letter in letters:
    counts1 += s1.count(letter)
    counts2 += s2.count(letter)
    counts += min(counts1, counts2)
    counts1 = 0
    counts2 = 0
print(counts)

answered May 30, 2017 at 18:37

Sepehr NazariSepehr Nazari

3,6754 gold badges11 silver badges17 bronze badges

0

Here is another way to do it using no modules.

sum(1 for i in zip(sorted(list(s1)), sorted(list(s2))) if len(set(i)) < 2)

3

answered May 30, 2017 at 18:43

Count number of common letters in two words in python

gold_cygold_cy

12.7k3 gold badges21 silver badges42 bronze badges

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)

answered Dec 28, 2018 at 21:41

1

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

answered Apr 27, 2021 at 14:27

0Knowledge0Knowledge

7193 silver badges11 bronze badges

How do you count the common characters in two strings?

Approach: Count the frequencies of all the characters from both strings. Now, for every character if the frequency of this character in string s1 is freq1 and in string s2 is freq2 then total valid pairs with this character will be min(freq1, freq2). The sum of this value for all the characters is the required answer.

How do you count occurrences of a word in a string in Python?

The count() method returns the number of occurrences of a substring in the given string..
substring - string whose count is to be found..
start (Optional) - starting index within the string where search starts..
end (Optional) - ending index within the string where search ends..

How do you count occurrences of a letter in Python?

Use the count() Function to Count the Number of a Characters Occuring in a String in Python. We can count the occurrence of a value in strings using the count() function. It will return how many times the value appears in the given string.

How do you count similar characters in a string?

Python.
string = "Great responsibility";.
print("Duplicate characters in a given string: ");.
#Counts each character present in the string..
for i in range(0, len(string)):.
count = 1;.
for j in range(i+1, len(string)):.
if(string[i] == string[j] and string[i] != ' '):.
count = count + 1;.