- Python Basic Programs
- Python Program Examples
- Python Print Hello World
- Python Get Input from User
- Python Add Two Numbers
- Add Subtract Multiply Divide
- Python Check Even or Odd
- Python Check Prime or Not
- Python Check Alphabet or Not
- Python Check Vowel or Not
- Python Check Leap Year or Not
- Check Reverse equal Original
- Check Positive Negative Zero
- Python Check Armstrong or Not
- Python Check Palindrome or Not
- Python Check Perfect Number
- Python Find Reverse of Number
- Python Count Digits in Number
- Python Add Digits of Number
- Sum of First and Last Digits
- Python Product of Mid Digits
- Sum of Squares of Digits
- Interchange Digits of Number
- Python Sum of n Numbers
- Python Print ASCII Values
- Python Swap Two Numbers
- Python Swap Two Variables
- Python Fahrenheit to Celsius
- Python Celsius to Fahrenheit
- Python Display Calendar
- Python Days into Years, Weeks
- Find Largest of Two Number
- Find Largest of Three Number
- Python Print Fibonacci Series
- Generate Armstrong Numbers
- Python Make Simple Calculator
- Python Add Binary Numbers
- Binary Number Multiplication
- Python Mathematical Programs
- Find Sum of Natural Numbers
- Find Average of n Numbers
- Python Print Multiplication Table
- Print Table using Recursion
- Python Find Average Percentage
- Python Find Grade of Student
- Find Square Root of Number
- Python Print Prime Numbers
- Find Numbers Divisible by
- Python Find Factors of Number
- Python Find Factorial of a Number
- Python Find HCF & LCM
- Python Kilometres to Miles
- Python Find Area of Square
- Python Find Area of Rectangle
- Python Find Area of Triangle
- Python Find Area of Circle
- Python Find Perimeter of Square
- Find Perimeter of Rectangle
- Python Find Perimeter of Triangle
- Find Circumference of Circle
- Python Simple Interest
- Python Solve Quadratic Equation
- Python Different Set of Operations
- Python Display Powers of 2
- Python Find nCr & nPr
- Python Pattern Programs
- Python Print Pattern Programs
- Python Print Diamond Pattern
- Python Print Floyd's Triangle
- Python Print Pascal's Triangle
- Python List Programs
- Python Count Even/Odd in List
- Python Positive/Negative in List
- Python Even Numbers in List
- Python Odd Numbers in List
- Python Sum of Elements in List
- Sum of Odd/Even Numbers
- Python Element at Even Position
- Python Element at Odd Position
- Python Search Element in List
- Python Largest Number in List
- Python Smallest Number in List
- Python Second Largest in List
- Python Second Smallest in List
- Python Insert Element in List
- Python Delete Element from List
- Python Multiply Numbers in List
- Swap Two Elements in List
- Python 1D Array Program
- Python Linear Search
- Python Binary Search
- Python Insertion Sort
- Python Bubble Sort
- Python Selection Sort
- Remove Duplicates from List
- Python Reverse a List
- Python Merge Two List
- Python Copy a List
- Python Conversion Programs
- Python Decimal to Binary
- Python Decimal to Octal
- Python Decimal to Hexadecimal
- Python Binary to Decimal
- Python Binary to Octal
- Python Binary to Hexadecimal
- Python Octal to Decimal
- Python Octal to Binary
- Python Octal to Hexadecimal
- Python Hexadecimal to Decimal
- Python Hexadecimal to Binary
- Python Hexadecimal to Octal
- Python Matrix Programs
- Python Add Two Matrices
- Python Subtract Two Matrices
- Python Transpose Matrix
- Python Multiply Matrices
- Python String Programs
- Python Print String
- Python Find Length of String
- Python Compare Two Strings
- Python Copy String
- Python Concatenate String
- Python Reverse a String
- Python Swap Two Strings
- Python Uppercase to Lowercase
- Python Lowercase to Uppercase
- Python Check Substring in String
- Python Count Character in String
- Count Repeated Characters
- Python Count Word in Sentence
- Python Count Each Vowels
- Python Capitalize Character
- Python Capitalize Word in String
- Python Smallest/Largest Word
- Remove Spaces from String
- Remove Duplicate Character
- Remove Vowels from String
- Remove Punctuation from String
- Python Remove Word in String
- Python Remove Duplicate Words
- WhiteSpace to Hyphens
- Replace Vowels with Character
- Replace Character in String
- Python Sort String in Alphabetical
- Sort Word in Alphabetical Order
- Extract Number from String
- Python Check Anagram Strings
- Python File Programs
- Python Read a File
- Python Write to File
- Python Append Text to File
- Python Copy Files
- Python Merge Two Files
- Python Counts Characters in File
- Python Count Words in File
- Python File Content in Reverse
- Python Lines Contains String
- Python Delete Line from File
- Python Capitalize Word in File
- Python Replace Text in File
- Replace Specific Line in File
- Python Find Size of File
- Python List Files in Directory
- Python Delete Files
- Python Misc Programs
- Python Reverse a Tuple
- Python Merge Two Dictionary
- Python bytes to String
- Python bytearray to String
- Generate Random Numbers
- Python Print Address of Variable
- Python Print Date and Time
- Python Get IP Address
- Python Shutdown/Restart PC
- Python Tutorial
- Python Tutorial
Python Program to Check Two Strings are Anagram or Not
This article is created to cover some programs in Python, that receives two strings by user at run-time, and checks whether two strings are anagram or not. Here are the list of programs:
- Check Two Strings are Anagram or Not using for loop, without sorting the string
- Using sorted() Function
- Using user-defined Function
- Using Class
Before created these programs, let's first understand about anagram.
What are Anagram Strings ?
Two strings can be called as anagram, when:
- both contains the same number of characters
- order of characters doesn't matter
- one string can be rearranged to form the other one
For Example, abc and cba are two anagram strings. Similarly, creative and reactive are also anagram. That is, characters of creative can be rearranged to form reactive and vice-versa.
Check Two Strings are Anagram using for Loop
This program is created using for loop to check whether the two strings entered by user are anagram or not. The question is, write a Python program to check Anagram or not without sorting the string. Here is its answer:
print("Enter the First String:") textOne = str(input()) print("Enter the Second String:") textTwo = str(input()) found=0 notFound=0 lenOne = len(textOne) lenTwo = len(textTwo) if lenOne == lenTwo: for i in range(lenOne): found = 0 for j in range(lenOne): if textOne[i] == textTwo[j]: found = 1 break if found==0: notFound = 1 break if notFound==1: print("\nStrings are Not Anagram") else: print("\nStrings are Anagram") else: print("\nLength of Strings are not Equal")
Here is its sample run:
Now supply two strings input say listen as first and silent as second string and press ENTER
key to check and print whether these two strings are anagram or not as shown in the snapshot given below:
Here is another sample run with user input listen and silenx as first and second string:
And here is the third sample run with user input codes and cracker as first and second string:
Note - The str() method is used to convert any type of value to a string type. And len() method returns length of string passed as its argument.
The dry run of above program with user input listen and silent, goes like:
- Initial values, textOne = listen (entered by user), textTwo = silent (entered by user), found = 0, notFound = 0
- Now using len() method, the length of first and second string gets initialized to lenOne and lenTwo variables. So lenOne=6 and lenTwo=6
- Since the condition (of if) lenOne == lenTwo or 6 == 6 evaluates to be true, therefore program flow goes inside this if's body
- The range() returns a sequence of values, starting with 0 and increments by 1 each time, by default. Continues until lenOne-1, since lenOne provided as its argument
- Therefore at first execution i's value is 0, so i<lenOne or 0<6 evaluates to be true, therefore program flow goes inside this for loop's body
- And 0 gets initialized to found. Now there is another for loop that gets executed
- So j=0 and since 0 is less than lenOne's value, therefore the condition evaluates to be true, and program flow goes inside this for loop's body
- Inside this loop, I've compared the character at current index of first string to all characters of second string. That is, if the character of first string gets matches to any character of second string, then 1 gets stored to found and using break keyword, remaining execution of this for loop gets skipped
- And using found==0 condition, we've checked whether program flow goes inside previous if's body or not. That is, if previous if's condition evaluates to be true, then we've to continue, otherwise, initialize 1 to notFound and using break keyword, skip remaining execution of outer for loop
- In this way, I've compared in character by character manner, and checked whether two strings entered by user are anagram or not
- Since each and every characters of first string is available in second string, therefore program flow never goes inside the body of if whose condition is found==0. So that 1 never gets initialized to notFound variable. And the condition notFound==1 doesn't evaluates to be true, therefore else's statement gets executed
- That prints Strings are Anagram
Modified Version of Previous Program
This program uses sorted() method to sort the string and compares strings in character by character manner, to check whether two strings are anagram or not. The end= is used to skip inserting an automatic newline using print()
print(end="Enter the First String: ") textOne = str(input()) print(end="Enter the Second String: ") textTwo = str(input()) lenOne = len(textOne) lenTwo = len(textTwo) notFound=0 if lenOne == lenTwo: textOne = sorted(textOne) textTwo = sorted(textTwo) for i in range(lenOne): if textOne[i] != textTwo[i]: notFound=1 break if notFound==0: print("\nStrings are Anagram") else: print("\nStrings are Not Anagram") else: print("\nLength of Strings are not Equal")
Here is its sample run with user input creative and reactive as two strings:
Check Anagram Strings using sorted()
This program uses sorted() method to do the same job as previous program does. The two strings entered by user gets compared directly using == operator.
print("Enter First String: ", end="") textOne = str(input()) print("Enter Second String: ", end="") textTwo = str(input()) lenOne = len(textOne) lenTwo = len(textTwo) if lenOne == lenTwo: if sorted(textOne) == sorted(textTwo): print("\nStrings are Anagram") else: print("\nStrings are Not Anagram") else: print("\nLength of Strings are not Equal")
Here is its sample run with user input sadder and dreads:
Check Anagram Strings using Function
This program is created using user-defined function named CheckAnag(). The function receives two strings as its argument and returns 1 if both strings are anagram.
def CheckAnag(sOne, sTwo): if sorted(sOne) == sorted(sTwo): return 1 print("Enter First String: ", end="") textOne = str(input()) print("Enter Second String: ", end="") textTwo = str(input()) rVal = CheckAnag(textOne, textTwo) if rVal==1: print("\nStrings are Anagram") else: print("\nStrings are Not Anagram")
Check Anagram Strings using Class
This is the last program created using class, an object-oriented feature of Python. To access member function of a class, an object is required. Therefore an object named obj is created of class fresherearth to access its member function named CheckAnag() using dot (.) operator.
class fresherearth: def CheckAnag(self, sOne, sTwo): if sorted(sOne) == sorted(sTwo): return 1 print("Enter First String: ", end="") textOne = str(input()) print("Enter Second String: ", end="") textTwo = str(input()) obj = fresherearth() rVal = obj.CheckAnag(textOne, textTwo) if rVal==1: print("\nStrings are Anagram") else: print("\nStrings are Not Anagram")
« Previous Program Next Program »