Tuesday, November 19, 2019

Python Program to Check if Strings Anagram or Not

In this post we'll see a Python program to check if two strings are anagrams or not.

Anagram Strings

Two strings are called anagram if you can rearrange the letters of one string to produce the second string, using all the letters of the first string only once. While doing that, usually, you don't consider spaces and punctuation marks.

Some Examples- "keep" and "peek", "silent" and "listen", "School Master" and "The Classroom".

Strings Anagram or not Python program

Python program to check whether the given strings are anagrams or not can be written by using one of the following options.

  1. Sorting both the strings
  2. By iterating one of the string character by character and verifying that the second string has the same characters present.

1. By sorting string

If you are using sorting logic to find whether strings are anagram or not in Python, just sort both the strings and compare if content is equal that means strings are anagram.

You can use sorted() in built function in Python to sort which returns a new sorted list from the items in iterable. Before sorting the string you can also change the case of the strings and remove spaces from the string.

import re


def is_anagram(s1, s2):
    # change to Lower case and remove leading, trailing
    # and spaces in between
    temp1 = re.sub("^\\s+|\\s+$|\\s+", "", s1.lower())
    temp2 = re.sub("^\\s+|\\s+$|\\s+", "", s2.lower())
    print('s1 in lower case and no spaces-', temp1)
    print('s2 in lower case and no spaces-', temp2)

    if sorted(temp1) == sorted(temp2):
        print(s1, 'and', s2, 'are anagrams')
    else:
        print(s1, 'and', s2, 'are not anagrams')


is_anagram('silent', 'listen')
is_anagram('School Master', 'The Classroom')
is_anagram('Peak', 'Keep')

Output

s1 in lower case and no spaces- silent
s2 in lower case and no spaces- listen
silent and listen are anagrams
s1 in lower case and no spaces- schoolmaster
s2 in lower case and no spaces- theclassroom
School Master and The Classroom are anagrams
s1 in lower case and no spaces- peak
s2 in lower case and no spaces- keep
Peak and Keep are not anagrams

2. By Iteration

If you are using loop to find whether strings are anagram or not in Python, then iterate one string char by char and check whether that character exists in another string or not, for that you can use find() method.

If character exists in the second string then delete that occurrence of the character from the string too so that same character is not found again (if char occurs more than once).

import re


def is_anagram(s1, s2):
    # change to Lower case and remove leading, trailing
    # and spaces in between
    temp1 = re.sub("^\\s+|\\s+$|\\s+", "", s1.lower())
    temp2 = re.sub("^\\s+|\\s+$|\\s+", "", s2.lower())
    print('s1 in lower case and no spaces-', temp1)
    print('s2 in lower case and no spaces-', temp2)
    # if both strings are not of same length then not anagrams
    if len(temp1) != len(temp2):
        print(s1, 'and', s2, 'are not anagrams')

    for c in temp1:
        index = temp2.find(c);
        if index == -1:
            print(s1, 'and', s2, 'are not anagrams')
            break
        else:
            # delete the foud character so that same character is
            # not found again
            temp2.replace(c, "", 1)
    else:
        print(s1, 'and', s2, 'are anagrams')


is_anagram('Hello', 'OHell')
is_anagram('School Master', 'The Classroom')
is_anagram('Peak', 'Keep')

Output

s1 in lower case and no spaces- hello
s2 in lower case and no spaces- ohell
Hello and OHell are anagrams
s1 in lower case and no spaces- schoolmaster
s2 in lower case and no spaces- theclassroom
School Master and The Classroom are anagrams
s1 in lower case and no spaces- peak
s2 in lower case and no spaces- keep
Peak and Keep are not anagrams

That's all for this topic Python Program to Check if Strings Anagram or Not. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Programs Page


Related Topics

  1. Python Program to Check Armstrong Number
  2. Python Program to Check Whether String is Palindrome or Not
  3. Python Program to Check Prime Number
  4. Removing Spaces From String in Python
  5. Accessing Characters in Python String

You may also like -

  1. Python continue Statement With Examples
  2. Polymorphism in Python
  3. Functions in Python
  4. Constructor in Python - __init__() function
  5. Switch Case Statement in Java
  6. HashMap in Java With Examples
  7. Converting Numbers to Words - Java Program
  8. Configuring DataSource in Spring Framework