Anagram Substring Search using Python


In this tutorial, we are going to write a program which searches for all the anagram from a string.

See some examples.

Input:
anagram = "cat"
string = "tacghactcat"
Output:
Anagram at 0
Anagram at 5
Anagram at 7
Anagram at 8

Let's see how to write the code. Follow the below steps to write code.

Algorithm

1. Initialize two strings.
2. Create a function which returns whether two strings are anagram to each other or not.
3. Iterate through the main string in which we have to search for the anagrams.
   3.1. Check whether substring is an anagram or not using the function that we have defined.
      3.1.1. If True, print the starting index.

Examine the code if you feel difficult to write.

Example

# importing collections to check for anagrams
import collections
# initializing two strings
anagram = 'cat'
string = 'tacghactcat'
# function to check for anagrams
def is_anagram(string):
   # checking for anagram
   if collections.Counter(anagram) == collections.Counter(string):
      # returning True if anagrams
      return True
   else:
      # returning False if not
      return False
# getting lengths of both strings
anagram_len = len(anagram)
string_len = len(string)
# iterarint through the string
for i in range(string_len - anagram_len + 1):
   # checking for anagram
   if is_anagram(string[i:i+anagram_len]):
      # printing the index
      print(f'Anagram at {i}')

Output

If you run the above program, you will get the following results.

Anagram at 0
Anagram at 5
Anagram at 7
Anagram at 8

Conclusion

If you have doubts regarding the tutorial, mention them in the comment section.

Updated on: 04-Nov-2019

142 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements