Anagram In Python














































Anagram In Python



.An Anagram is a word or a phrase that can be formed by rearranging the letters of another word
For example :

input 1: cppsecrets
input 2: srectespcp
output: Yes 

METHOD 1 : 

  1. By counting the frequency of each character in both strings using dictionaries.
  2. Compare both dictionaries.
    def anagram():

   #Taking inputs
    Str_a = input()
    Str_b = input()

    #If lengths of both string doesn't equal then they can't be anagram
    if len(Str_a) != len(Str_b) :
            return 0

    #Initilising empty dictionary for Str_a
    d_a = {}
    
    # Loop through every character in Str_a and count no. of times each character appeared
    for ch in Str_a:
        if ch in d_a:
            d_a[ch] = d_a[ch]+1
        else :
            d_a[ch] = 1

    #Initilising empty dictionary for Str_b
    d_b = {}

    # Loop through every character in Str_b
    for ch_b in Str_b:
        if ch_b in d_b:
            d_b[ch_b] = d_b[ch_b]+1
        else :
            d_b[ch_b] = 1

    #Comparing both dictionaries
    if(d_a == d_b):
        return "YES,it is an anagram"
    else :
        return "NO"

METHOD 2 (USE SORTING) :

  1. Sort both strings
  2. Compare the sorted strings 
def areAnagram(str1, str2):
    # Get lengths of both strings
    n1 = len(str1)
    n2 = len(str2)
 
    # If length of both strings is not the same, then
    # they cannot be an anagram
    if n1 != n2:
        return 0
 
    # Sort both strings
    str1 = sorted(str1)
    str2 = sorted(str2)
 
    # Compare sorted strings
    for i in range(0, n1):
        if str1[i] != str2[i]:
            return 0
 
    return 1
 
 
# Driver code
str1 = "cppsecrets"
str2 = "srectespcp"
 
# Function Call
if areAnagram(str1, str2):
    print("The two strings are an anagram of each other")
else:
    print("The two strings are not an anagram of each other")

  This article is written by Rohit Bansal Intern at CPPSECRETS

Comments