Python – Similar characters Strings comparison
Last Updated :
12 Apr, 2023
Given two Strings, separated by delim, check if both contain same characters.
Input : test_str1 = 'e!e!k!s!g', test_str2 = 'g!e!e!k!s', delim = '!'
Output : True
Explanation : Same characters, just diff. positions.
Input : test_str1 = 'e!e!k!s', test_str2 = 'g!e!e!k!s', delim = '!'
Output : False
Explanation : g missing in 1st String.
Method #1 : Using sorted() + split()
In this, we perform split using split(), and then perform the task of sorting to get strings in order, post that strings are compared using the comparison operator.
Python3
test_str1 = 'e:e:k:s:g'
test_str2 = 'g:e:e:k:s'
print ( "The original string 1 is : " + str (test_str1))
print ( "The original string 2 is : " + str (test_str2))
delim = ':'
res = sorted (test_str1.split( ':' )) = = sorted (test_str2.split( ':' ))
print ( "Are strings similar : " + str (res))
|
Output
The original string 1 is : e:e:k:s:g
The original string 2 is : g:e:e:k:s
Are strings similar : True
Time Complexity: O(n) -> (split function)
Auxiliary Space: O(n)
Method #2 : Using set() + split()
In this, instead of sort(), we convert strings to set(), to get ordering. This works only on unique character strings.
Python3
test_str1 = 'e:k:s:g'
test_str2 = 'g:e:k:s'
print ( "The original string 1 is : " + str (test_str1))
print ( "The original string 2 is : " + str (test_str2))
delim = ':'
res = set (test_str1.split( ':' )) = = set (test_str2.split( ':' ))
print ( "Are strings similar : " + str (res))
|
Output
The original string 1 is : e:k:s:g
The original string 2 is : g:e:k:s
Are strings similar : True
Time Complexity: O(n) -> (split function)
Auxiliary Space: O(n)
Method #3: Using dictionary
In this approach, we can use dictionaries to count the frequency of each character in both the strings. Then, we can compare the frequency of each character between the two dictionaries to check if the strings have the same characters or not.
Here are the steps:
- Initialize two dictionaries, one for each string.
- Split the strings into characters using the delimiter ‘:’ and loop through the characters of each string.
- For each character, check if it is already present in the dictionary. If it is not present, add it with a value of 1. If it is already present, increment its value by 1.
- After both dictionaries are created, compare them by looping through each key in one dictionary and checking if the key exists in the other dictionary with the same value. If all keys and values match, return True. Otherwise, return False.
- Print the result.
Python3
test_str1 = 'e:k:s:g'
test_str2 = 'g:e:k:s'
print ( "The original string 1 is : " + str (test_str1))
print ( "The original string 2 is : " + str (test_str2))
delim = ':'
dict1 = {}
dict2 = {}
for char in test_str1.split(delim):
if char in dict1:
dict1[char] + = 1
else :
dict1[char] = 1
for char in test_str2.split(delim):
if char in dict2:
dict2[char] + = 1
else :
dict2[char] = 1
res = True
for key in dict1:
if key in dict2 and dict1[key] = = dict2[key]:
continue
else :
res = False
break
print ( "Are strings similar : " + str (res))
|
Output
The original string 1 is : e:k:s:g
The original string 2 is : g:e:k:s
Are strings similar : True
Time complexity: O(n), where n is the length of the longer string (as we are looping through each character in each string once).
Auxiliary space: O(k), where k is the number of unique characters in both strings (as we are creating dictionaries to store the frequency of each character).
Method 4: using the Counter() function from the collections module.
This approach involves the following steps:
- Import the collections module.
- Initialize the two strings to be compared.
- Initialize an empty dictionary for each string.
- Use the Counter() function to count the frequency of each character in both strings and store the results in the corresponding dictionary.
- Compare the two dictionaries to check if they have the same keys with the same frequency of values.
- Print the result.
Python3
from collections import Counter
test_str1 = 'e:k:s:g'
test_str2 = 'g:e:k:s'
print ( "The original string 1 is : " + str (test_str1))
print ( "The original string 2 is : " + str (test_str2))
dict1 = {}
dict2 = {}
dict1 = Counter(test_str1)
dict2 = Counter(test_str2)
res = dict1 = = dict2
print ( "Are strings similar : " + str (res))
|
Output
The original string 1 is : e:k:s:g
The original string 2 is : g:e:k:s
Are strings similar : True
Time complexity: The time complexity of this approach is O(n), where n is the length of the longest string.
Auxiliary space: The auxiliary space required by this approach is O(k), where k is the number of unique characters in both strings.
Method 5 : Using list comprehension and all()
step-by-step approach of the code:
- Initialize two strings: test_str1 and test_str2.
- Initialize a delimiter as : in delim variable.
- Split test_str1 and test_str2 strings based on delimiter using the split() method and store the resulting lists in list1 and list2 respectively.
- Check if all characters in list1 are present in list2 using a list comprehension and the all() function.
- Similarly, check if all characters in list2 are present in list1.
- Store the result of the check in a variable called res.
- Print the result of the comparison by converting the boolean value of res to a string using str() function and concatenating it with the string “Are strings similar : “.
Python3
test_str1 = 'e:k:s:g'
test_str2 = 'g:e:k:s'
delim = ':'
list1 = test_str1.split(delim)
list2 = test_str2.split(delim)
res = all (char in list2 for char in list1) and all (char in list1 for char in list2)
print ( "Are strings similar : " + str (res))
|
Output
Are strings similar : True
Time complexity: O(n^2) where n is the length of the longer string (due to the all() function in the list comprehension)
Auxiliary space: O(n) where n is the length of the longer string (for the two lists created in memory)
Similar Reads
Python | Kth index character similar Strings
Sometimes, we require to get the words that have the Kth index with the specific letter. This kind of use case is quiet common in places of common programming projects or competitive programming. Letâs discuss certain shorthand to deal with this problem in Python. Method #1: Using list comprehension
3 min read
Python | Strings with similar front and rear character
Sometimes, while programming, we can have a problem in which we need to check for the front and rear characters of each string. We may require to extract the count of all strings with similar front and rear characters. Let's discuss certain ways in which this task can be performed. Method #1: Using
4 min read
Similarity Metrics of Strings - Python
In Python, we often need to measure the similarity between two strings. For example, consider the strings "geeks" and "geeky" âwe might want to know how closely they match, whether for tasks like comparing user inputs or finding duplicate entries. Let's explore different methods to compute string si
3 min read
Python | Ways to check string contain all same characters
Given a list of strings, write a Python program to check whether each string has all the characters same or not. Given below are a few methods to check the same. Method #1: Using Naive Method [Inefficient] C/C++ Code # Python code to demonstrate # to check whether string contains # all characters sa
5 min read
Python program to check a string for specific characters
Here, will check a string for a specific character using different methods using Python. In the below given example a string 's' and char array 'arr', the task is to write a python program to check string s for characters in char array arr. Examples: Input: s = @geeksforgeeks% arr[] = {'o','e','%'}O
4 min read
Python - Check if string contains character
In Python, we can check if a string contains a character using several methods. in operator is the simplest and most commonly used way. If we need more control, methods like find(), index(), and count() can also be useful. Using in Operator in operator is the easiest way to check if a character exis
2 min read
Python - Characters occurring in multiple Strings
Sometimes, while working with Python strings, we can have problem in which we need to extract the characters which have occurrences in more than one string in string list. This kind of problem usually occurs in web development and Data Science domains. Lets discuss certain ways in which this task ca
5 min read
Python - Sort Strings by maximum frequency character
Given a string, the task is to write a Python program to perform sort by maximum occurring character. Input : test_list = ["geekforgeeks", "bettered", "for", "geeks"] Output : ['for', 'geeks', 'bettered', 'geekforgeeks'] Explanation : 1 < 2 < 3 < 4, is ordering of maximum character occurren
3 min read
Python Program to check for almost similar Strings
Given two strings, the task here is to write a python program that can test if they are almost similar. Similarity of strings is being checked on the criteria of frequency difference of each character which should be greater than a threshold here represented by K. Input : test_str1 = 'aabcdaa', test
5 min read
Python - Check for spaces in string
Sometimes, while working with strings in Python, we need to determine if a string contains any spaces. This is a simple problem where we need to check for the presence of space characters within the string. Let's discuss different methods to solve this problem. Using 'in' operator'in' operator is on
3 min read