Open In App

Python – Similar characters Strings comparison

Last Updated : 12 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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




# Python3 code to demonstrate working of
# Similar characters Strings comparison
# Using split() + sorted()
 
# initializing strings
test_str1 = 'e:e:k:s:g'
test_str2 = 'g:e:e:k:s'
 
# printing original strings
print("The original string 1 is : " + str(test_str1))
print("The original string 2 is : " + str(test_str2))
 
# initializing delim
delim = ':'
 
# == operator is used for comparison
res = sorted(test_str1.split(':')) == sorted(test_str2.split(':'))
 
# printing result
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




# Python3 code to demonstrate working of
# Similar characters Strings comparison
# Using set() + split()
 
# initializing strings
test_str1 = 'e:k:s:g'
test_str2 = 'g:e:k:s'
 
# printing original strings
print("The original string 1 is : " + str(test_str1))
print("The original string 2 is : " + str(test_str2))
 
# initializing delim
delim = ':'
 
# == operator is used for comparison
# removes duplicates and compares
res = set(test_str1.split(':')) == set(test_str2.split(':'))
 
# printing result
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:

  1. Initialize two dictionaries, one for each string.
  2. Split the strings into characters using the delimiter ‘:’ and loop through the characters of each string.
  3. 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.
  4. 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.
  5. Print the result.

Python3




# Python3 code to demonstrate working of
# Similar characters Strings comparison
# Using dictionary
 
# initializing strings
test_str1 = 'e:k:s:g'
test_str2 = 'g:e:k:s'
 
# printing original strings
print("The original string 1 is : " + str(test_str1))
print("The original string 2 is : " + str(test_str2))
 
# initializing delim
delim = ':'
 
# initializing dictionaries
dict1 = {}
dict2 = {}
 
# loop through characters in string 1
for char in test_str1.split(delim):
    if char in dict1:
        dict1[char] += 1
    else:
        dict1[char] = 1
 
# loop through characters in string 2
for char in test_str2.split(delim):
    if char in dict2:
        dict2[char] += 1
    else:
        dict2[char] = 1
 
# compare dictionaries
res = True
for key in dict1:
    if key in dict2 and dict1[key] == dict2[key]:
        continue
    else:
        res = False
        break
 
# printing result
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:

  1. Import the collections module.
  2. Initialize the two strings to be compared.
  3. Initialize an empty dictionary for each string.
  4. Use the Counter() function to count the frequency of each character in both strings and store the results in the corresponding dictionary.
  5. Compare the two dictionaries to check if they have the same keys with the same frequency of values.
  6. Print the result.

Python3




# Importing the collections module
from collections import Counter
 
# Initializing strings
test_str1 = 'e:k:s:g'
test_str2 = 'g:e:k:s'
 
# Printing original strings
print("The original string 1 is : " + str(test_str1))
print("The original string 2 is : " + str(test_str2))
 
# Initializing empty dictionaries
dict1 = {}
dict2 = {}
 
# Counting the frequency of each character in both strings and storing the results in the corresponding dictionary
dict1 = Counter(test_str1)
dict2 = Counter(test_str2)
 
# Comparing the two dictionaries to check if they have the same keys with the same frequency of values
res = dict1 == dict2
 
# Printing result
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:

  1. Initialize two strings: test_str1 and test_str2.
  2. Initialize a delimiter as : in delim variable.
  3. Split test_str1 and test_str2 strings based on delimiter using the split() method and store the resulting lists in list1 and list2 respectively.
  4. Check if all characters in list1 are present in list2 using a list comprehension and the all() function.
  5. Similarly, check if all characters in list2 are present in list1.
  6. Store the result of the check in a variable called res.
  7. 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




# initializing strings
test_str1 = 'e:k:s:g'
test_str2 = 'g:e:k:s'
 
# initializing delimiter
delim = ':'
 
# convert strings to lists of characters
list1 = test_str1.split(delim)
list2 = test_str2.split(delim)
 
# check if both lists have the same characters
res = all(char in list2 for char in list1) and all(char in list1 for char in list2)
 
# printing result
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

Combine similar characters in Python using Dictionary Get() Method
Let us see how to combine similar characters in a list. Example : Input : ['g', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'g', 'e', 'e', 'k', 's'] Output : ['gg', 'eeee', 'kk', 'ss', 'f', 'o', 'r'] We will be using the get() method of the dictionary class. dictionary.get() The get() method returns the value of the item with the specified key. Syntax : dic
3 min read
Python Program to Split joined consecutive similar characters
Given a String, our task is to write a Python program to split on the occurrence of a non-similar character. Input : test_str = 'ggggffggisssbbbeessssstt'Output : ['gggg', 'ff', 'gg', 'i', 'sss', 'bbb', 'ee', 'sssss', 'tt']Explanation : All similar consecutive characters are converted to separate strings. Input : test_str = 'ggggffgg'Output : ['ggg
5 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 loop This is a brute force method by which this ta
4 min read
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 + lower() This problem can be solved using the co
3 min read
Python - Remove similar index elements in Strings
Given two strings, removed all elements from both, which are the same at similar index. Input : test_str1 = 'geels', test_str2 = 'beaks' Output : gel, bak Explanation : e and s are removed as occur in same indices. Input : test_str1 = 'geeks', test_str2 = 'geeks' Output : '', '' Explanation : Same strings, all same index, hence removed. Method #1 :
6 min read
Python - Filter Similar Case Strings
Given the Strings list, the task is to write a Python program to filter all the strings which have a similar case, either upper or lower. Examples: Input : test_list = ["GFG", "Geeks", "best", "FOr", "all", "GEEKS"] Output : ['GFG', 'best', 'all', 'GEEKS'] Explanation : GFG is all uppercase, best is all lowercase. Input : test_list = ["GFG", "Geeks
9 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_str2 = "abbaccd", K = 2Output : TrueExplanation :
5 min read
Python | Convert list of strings and characters to list of characters
Sometimes we come forward to the problem in which we receive a list that consists of strings and characters mixed and the task we need to perform is converting that mixed list to a list consisting entirely of characters. Let's discuss certain ways in which this is achieved. Method #1 : Using List comprehension In this method, we just consider each
6 min read
Python | Data Comparison and Selection in Pandas
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages, and makes importing and analyzing data much easier. The most important thing in Data Analysis is comparing values and selecting data accordingly. The "==" operator works for multiple valu
2 min read
Python | Excel File Comparison
Given Two Excel Files, We want to compare the values of each column row-wise after sorting the values and print the changed column name and row number and values change. Input : Two Excel files Output : Column name : 'location' and Row Number : 0 Column name : 'location' and Row Number : 3 Column name : 'date' and Row Number : 1 Code : Python code
1 min read
Practice Tags :