Using Counter() in Python 3.x. to find minimum character removal to make two strings anagram

PythonServer Side ProgrammingProgramming

In this article, we will learn about how we can make a string into a pangram using the counter() function in Python 3.x. Or earlier. To do so we are allowed to remove any character from the input string. We will also find the number of such required characters to be removed to make the string into an anagram.

Two strings are said to be anagrams of each other when they contain the same type of alphabets in any random order.

The counter () method is present in the collection module available in Python. The prerequisite is to import the collections module to use the counter() function.

Algorithm

1. Conversion of input string into a dictionary type having characters as
keys and their frequency as values using Counter(inp_str) available in
the collections module.
2. Counting the total number of keys and counting the number of keys in
common to both dictionaries converted from input strings.
3. If no common keys are detected this means there is a need for removal
of (sum of the length of both dictionaries) characters from both the
input strings.
4. otherwise (max(length of both dictionaries) – number of Common keys
available ) will give the required number of characters to be removed

collections.Counter is a dictionary subclass to ensure automatic counting the letters by the interpreter. We don’t actually need to create the substrings or check whether they are anagrams manually.

Example

 Live Demo

# two strings become anagram
from collections import Counter
def convertAnagram(str_1, str_2):
   # conversion of strings to dictionary type
   dict_1 = Counter(str_1)
   dict_2 = Counter(str_2)
   keys_1 = dict_1.keys()
   keys_2 = dict_2.keys()
   # count number of keys in both lists of keys
   count_1 = len(keys_1)
   count_2 = len(keys_2)
   # convert pair of keys into set to find common keys
   set_1 = set(keys_1)
   commonKeys = len(set_1.intersection(keys_2))
   if (commonKeys == 0): # no common things found i.e. all are distinct
      return (count_1 + count_2)
   else: # some elements are already matching in input
      return (max(count_1, count_2)-commonKeys)
str_1 ='Tutorials'
str_2 ='sTutalori'
str_3='Point'
print (convertAnagram(str_1, str_2))
print (convertAnagram(str_3, str_2))

Output

0
6

Conclusion

In this article, we learnt how we can make two string anagram of one another by counting the number of characters needed for maintaining the anagram relationship Python 2.x. needed.

raja
Published on 29-Aug-2019 07:45:40
Advertisements