Count Common Characters in Strings Python

find uncommon characters of the two strings python
python compare two strings character by character
python program that displays which letters are in the two strings but not in both
python find common words in two strings
count the number of matching characters in a pair of string python
find difference between two strings python
find all common substrings python
python string overlap

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.

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

Python: How to count number of letters in a string?, How do you count characters in a string in python? Python code to print common characters of two Strings in alphabetical order Given two strings, print all the common characters in lexicographical order. If there are no common letters, print -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.

Finding common characters in two strings, How do you find common characters in two strings in python? The letters that are common between the two strings are o (1 times), p (1 time)

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.

Python String, Convert both strings into dictionary data type using Counter(str) method, which contains characters of string as key and their frequencies as value. Now find  Count common characters in two strings Given two strings s1 and s2 consisting of lowercase English alphabets, the task is to count all the pairs of indices (i, j) from the given strings such that s1[i] = s2[j] and all the indices are distinct i.e. if s1[i] pairs with some s2[j] then these two characters will not be paired with any other character.

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)

Python code to print common characters of two Strings in , Python code to count number of unique matching. # characters in a pair of strings​. # count function count the common unique. # characters present in both  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)

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

Python, Count of Common Characters in the Strings - python. Two string values S1 and S2 are passed as input. The program must print the count of  Python string method count () returns the number of occurrences of substring sub in the range [start, end]. Optional arguments start and end are interpreted as in slice notation.

Spicy Coders: Count of Common Characters in the Strings, If there are no common letters print 'No common characters'. from collections import Counter def common_chars(str1,str2): d1 = Counter(str1) Two strings: Python : PHP P Two strings: Java : PHP No common characters. Here, we are going to use some predefined functions to count the number of unique elements in a given string using python. set () is the predefined method used in this script. 1.set () method: set () method is unordered collection of unique elements of data.set () is used to eliminate duplicates from the list or string.

Python: Find all the common characters in lexicographical order , Above code will print all the common characters. But this method is not efficient because for each character we are scanning whole list. You can use maps or  Previous: Write a Python program to calculate the length of a string. Next: Write a Python program to get a string made of the first 2 and the last 2 chars from a given a string. If the string length is less than 2, return instead of the empty string.

How to find common characters between two strings in python, Enter two input strings and store it in separate variables. 2. Convert both of the strings into sets and find the common letters between both the sets. 3. Store the  String of ASCII characters which are considered printable. This is a combination of digits, ascii_letters, punctuation, and whitespace. string.whitespace¶ A string containing all ASCII characters that are considered whitespace. This includes the characters space, tab, linefeed, return, formfeed, and vertical tab.

Comments
  • what is it you're trying to achieve?
  • Can you explain why 3 is the correct answer?
  • In s1 there are 2 qs and 1 r that match s2. I just want the answer to output this.
  • see : stackoverflow.com/questions/9732515/…
  • I saw that and this is how I built my code. However, this does not give the answer I need.
  • gosh I love print statements
  • Your answer is correct. However, I like the simplicity of the top answer.
  • Thank you for contributing. Maybe you could add a short explanation to the code to help other readers and also explain why OP's code is wrong to help them improve.