Anagram Substring Search using Python

PythonServer Side ProgrammingProgramming

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

See some examples.

anagram = "cat"
string = "tacghactcat"
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.


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.


# 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
      # 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}')


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

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


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

Published on 04-Nov-2019 12:11:41