Write a program to check if the given strings are anagram or not.

Introduction

An anagram is a word or phrase formed by rearranging the letters of another word or phrase. Two strings are considered anagrams if they consist of the same characters with the same frequency, regardless of the order. For example, the words “listen” and “silent” are anagrams because both have the same characters arranged differently.

In this program, we will write a Python code that checks whether two given strings are anagrams. We will also explain the program line by line to ensure a clear understanding.

# Function to check if two strings are anagrams
def are_anagrams(str1, str2):
    # Remove any whitespace and convert both strings to lowercase
    str1 = str1.replace(" ", "").lower()
    str2 = str2.replace(" ", "").lower()

    # Check if the sorted characters of both strings are the same
    if sorted(str1) == sorted(str2):
        return True
    else:
        return False

# Input: Get two strings from the user
string1 = input("Enter the first string: ")
string2 = input("Enter the second string: ")

# Check if the strings are anagrams and print the result
if are_anagrams(string1, string2):
    print(f'"{string1}" and "{string2}" are anagrams.')
else:
    print(f'"{string1}" and "{string2}" are not anagrams.')
Python

Line-by-Line Explanation

If the function returns False, the program prints a message indicating that the two strings are not anagrams.

def are_anagrams(str1, str2):

This line defines a function named are_anagrams that takes two strings (str1 and str2) as input arguments. This function will check if these two strings are anagrams.

str1 = str1.replace(" ", "").lower() and str2 = str2.replace(" ", "").lower()

These lines remove any spaces from both strings using replace(" ", "") and convert all the characters to lowercase using .lower(). This ensures that we ignore case differences and spaces when checking for anagrams.

For example, if str1 = "Listen " and str2 = "Silent", after these operations, both strings will be converted to "listen" and "silent".

if sorted(str1) == sorted(str2):

The sorted() function sorts all the characters of the strings in alphabetical order. If both strings are anagrams, the sorted characters of both strings will be identical.

For example, sorted("listen") and sorted("silent") both result in ['e', 'i', 'l', 'n', 's', 't'], indicating that they are anagrams.

return True and return False

If the sorted characters of both strings are equal, the function returns True, indicating that the strings are anagrams.

Otherwise, it returns False, meaning the strings are not anagrams.

string1 = input("Enter the first string: ") and string2 = input("Enter the second string: ")

These lines prompt the user to input two strings. The input() function reads the user’s input and assigns it to the variables string1 and string2.

if are_anagrams(string1, string2):

This line calls the are_anagrams() function, passing the two user-input strings as arguments. The function will return True if the strings are anagrams and False if they are not.

print(f'"{string1}" and "{string2}" are anagrams.')

If the function returns True, the program prints a message indicating that the two strings are anagrams.

print(f'"{string1}" and "{string2}" are not anagrams.')

Example Output

Input 1: When the strings are anagrams

Enter the first string: listen
Enter the second string: silent
"listen" and "silent" are anagrams.
Python

Input 2: When the strings are not anagrams

Enter the first string: hello
Enter the second string: world
"hello" and "world" are not anagrams.
Python

Conclusion

This Python program efficiently checks whether two given strings are anagrams by comparing the sorted versions of the strings. By stripping spaces and converting to lowercase, the program ensures that the check is case-insensitive and space-agnostic. Understanding each part of the code helps you see how simple operations like sorting and string manipulation can be used to solve problems effectively.

By practicing and understanding basic Python functions like string manipulation and comparison, you can build more complex programs in the future. This anagram-checking program is a great introduction to how programming logic can be applied to common real-world problems.

Leave a Reply

Your email address will not be published. Required fields are marked *

Resize text
Scroll to Top