Open In App

Python | Count the Number of matching characters in a pair of string

Last Updated : 24 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Given a pair of non-empty strings. Count the number of matching characters in those strings (consider the single count for the character which have duplicates in the strings). 

Examples:

Input : str1 = 'abcdef'
str2 = 'defghia'
Output : 4
(i.e. matching characters :- a, d, e, f)

Input : str1 = 'aabcddekll12@'
str2 = 'bb2211@55k'
Output : 5
(i.e. matching characters :- b, 1, 2, @, k)

Approach 1: 1. Initialize a counter variable with 0. 2. Iterate over the first string from the starting character to ending character. 3. If the character extracted from first string is found in the second string and also first occurrence index of that extracted character in first string is same as that of index of current extracted character then increment the value of counter by 1.

Note: For this, use string.find(character) in python. This returns the first occurrence index of character in string, if found, otherwise return -1. For example : str=’abcdedde’ str.find(‘d’) –> 3 str.find(‘e’) –> 4 str.find(‘g’) –> -1

4. Output the value of counter. Below is the implementation of above approach. 

Python
// C++ code to count number of matching
// characters in a pair of strings

# include <bits/stdc++.h>
using namespace std

// Function to count the matching characters
void count(string str1, string str2)
{
    int c = 0, j = 0

    // Traverse the string 1 char by char
    for (int i=0
         i < str1.length()
         i++) {

        // This will check if str1[i]
        // is present in str2 or not
        // str2.find(str1[i]) returns - 1 if not found
        // otherwise it returns the starting occurrence
        // index of that character in str2
        if (str2.find(str1[i]) >= 0
            and j == str1.find(str1[i]))
        c += 1
        j += 1
    }
    cout << "No. of matching characters are: "
    << c / 2
}

// Driver code
int main()
{
    string str1 = "aabcddekll12@"
    string str2 = "bb2211@55k"

    count(str1, str2)
}

Output :

No. of matching characters are : 5

Approach 2: 1.In this approach set() is used to remove duplicate on a given string. 2.After that concept of set(intersection) is used on given string. 3.After that we find a length using len() method. 

Python3
# Python code to find no. of common characters between two strings

#first covert both string to set and then find common character between two
def commonfun(str1,str2):
    return(len((set(str1)).intersection(set(str2))))

#string1=input("Enter String 1 : ")
string1="VISHAV"
string2="VANSHIKA"
#string2=input("Enter String 2 : ")

no_of_common_character=commonfun(string1.lower(),string2.lower())

print("NO. OF COMMON CHRACTERS ARE : ",no_of_common_character)
    
#this code is contributed by VISHAV PRATAP SINGH RANA(UIET KURUKSHETRA)

Output :

NO. OF COMMON CHRACTERS ARE :  5

Approach 3:

  • Initialize a dictionary to keep count of each character in the first string.
  • Iterate over the first string and update the count of each character in the dictionary.
  • Initialize a counter variable with 0.
  • Iterate over the second string and check if the character is present in the dictionary and its count is greater than 0. If yes, increment the counter and decrement the count of the character in the dictionary.
  • Print the final value of the counter variable.
Python3
def count(str1, str2):
    # Initialize an empty dictionary to keep track of the count of each character in str1.
    char_count = {}

    # Iterate over each character in str1.
    for char in str1:
        # If the character is already in the dictionary, increment its count.
        if char in char_count:
            char_count[char] += 1
        # Otherwise, add the character to the dictionary with a count of 1.
        else:
            char_count[char] = 1

    # Initialize a counter variable to 0.
    counter = 0

    # Iterate over each character in str2.
    for char in str2:
        # If the character is in the char_count dictionary and its count is greater than 0, increment the counter and decrement the count.
        if char in char_count and char_count[char] > 0:
            counter += 1
            char_count[char] -= 1

    # Print the number of matching characters.
    print("No. of matching characters are: " + str(counter))

# Driver code
if __name__ == "__main__":
    # Define two strings to compare.
    str1 = 'aabcddekll12@'
    str2 = 'bb2211@55k'

    # Call the count function with the two strings.
    count(str1, str2)

Output
No. of matching characters are: 5

Time complexity: O(m+n), where m is the length of str1 and n is the length of str2. This is because we are iterating through each character in both strings once, and the time it takes to look up a character in a dictionary is constant.
Auxiliary space: O(k), where k is the number of distinct characters in str1. This is because we are creating a dictionary to store the count of each character in str1



Similar Reads

Python | Count of elements matching particular condition
Checking a number/element by a condition is a common problem one faces and is done in almost every program. Sometimes we also require to get the totals that match the particular condition to have a distinguish which to not match for further utilization. Lets discuss certain ways in which this task can be achieved. Method #1 : Using sum() + generato
5 min read
Python | Count of Matching i, j index elements
Sometimes, while programming, we can have a problem in which we need to check for ith and jth character of each string. We may require to extract count of all strings with similar ith and jth characters. Let’s discuss certain ways in which this task can be performed. Method #1 : Using loop This is brute force method by which this task can be perfor
4 min read
Python | Matching elements count
Sometimes, while working with lists we need to handle two lists and search for the matches, and return just the count of indices of the match. Querying whole list for the this process is not feasible when the size of master list is very large, hence having just the match indices helps in this cause. Let’s discuss certain ways in which this can be a
5 min read
Python - Count of matching elements among lists (Including duplicates)
Given 2 lists, count all the elements that are similar in both the lists including duplicated. Input : test_list1 = [3, 5, 6, 7, 2, 3, 5], test_list2 = [5, 5, 3, 9, 8, 5] Output : 4 Explanation : 3 repeats 2 times, and 5 two times, totalling to 4. Input : test_list1 = [3, 5, 6], test_list2 = [5, 3, 9] Output : 2 Explanation : 3 repeats 1 time, and
4 min read
Python | Get matching substrings in string
The testing of a single substring in a string has been discussed many times. But sometimes, we have a list of potential substrings and check which ones occur in a target string as a substring. Let's discuss certain ways in which this task can be performed. Method #1: Using list comprehension Using list comprehension is the naive and brute force met
6 min read
Python program to print k characters then skip k characters in a string
Given a String, extract K characters alternatively. Input : test_str = 'geeksgeeksisbestforgeeks', K = 4 Output : geekksisforg Explanation : Every 4th alternate range is sliced. Input : test_str = 'geeksgeeksisbest', K = 4 Output : geekksis Explanation : Every 4th alternate range is sliced. Method #1 : Using loop + slicing In this, we perform task
5 min read
Python program to count the number of characters in a String
Given a String. The task is to return the number of characters in the string. Examples: Input : test_str = 'geeksforgeeks !!$*** best 4 all Geeks 10-0' Output : 25Explanation : Only alphabets, when counted are 25 Input : test_str = 'geeksforgeeks !!$*** best for all Geeks 10---0' Output : 27Explanation : Only alphabets, when counted are 27 Method #
4 min read
Count the number of unique characters in a string in Python
Given a string S consisting of lowercase English alphabets, the task is to find the number of unique characters present in the string. Examples: Input: S = "geeksforgeeks" Output: 7 Explanation: The given string "geeksforgeeks" contains 6 unique characters {'g', 'e', 'k', 's', 'f', 'o', 'r'}.Input: S = "madam" Output: 3 Approach: The idea to solve
5 min read
Python | Remove first K elements matching some condition
Removal of elements in list can be performed using many inbuilt functions. Removing all or just a single occurrence removal both functions are present in Python library. This article discusses to remove just the first K occurrences of elements matching particular condition. Method #1: Naive Method We can append the elements that are matching condit
3 min read
Python Group by matching second tuple value in list of tuples
Given a list of tuples, the task is to group the tuples by matching the second element in the tuples. We can achieve this using dictionary by checking the second element in each tuple. Examples: Input : [(20, 80), (31, 80), (1, 22), (88, 11), (27, 11)] Output: {80: [(20, 80), (31, 80)], 11: [(88, 11), (27, 11)], 22: [(1, 22)]} Input : [(20, 'Geek')
3 min read