Python Program to Check whether two Strings are Anagrams

1. Introduction

Anagrams are a form of word play, where by rearranging the letters of one word or phrase, we produce another word or phrase. Detecting anagrams is a common task in software development, used in games, linguistics, and as a popular interview problem.

2. Problem

The challenge is to write a Python program that checks whether two given strings are anagrams of each other, considering that an anagram ignores any character that is not a letter and is case-insensitive.

3. Solution Steps

1. Create a function that sanitizes the input strings by removing non-letter characters and converting to lowercase.

2. Check if the sorted characters of the sanitized strings are equal.

3. Return the result.

4. Code Program

# Define the function to check if two strings are anagrams
def are_anagrams(str1, str2):
    # Sanitize the strings: remove non-letters and convert to lowercase
    sanitize = lambda s: ''.join(c for c in sorted(s.lower()) if c.isalpha())
    # Compare the sorted, sanitized strings
    return sanitize(str1) == sanitize(str2)

# Given strings
string1 = "listen"
string2 = "silent"

# Check if the strings are anagrams
anagram_status = are_anagrams(string1, string2)

# Print the result
print(f"Are '{string1}' and '{string2}' anagrams? {anagram_status}")

Output:

Are 'listen' and 'silent' anagrams? True

Explanation:

1. are_anagrams is the function that takes two strings, str1 and str2, as arguments.

2. A lambda function sanitize is defined to convert the strings to lowercase, sort them, and filter out non-alphabetic characters using isalpha().

3. The sanitize function is applied to both str1 and str2, and the equality of the resulting strings is checked.

4. string1 and string2 are initialized to "listen" and "silent", which are known anagrams.

5. anagram_status holds the boolean result from the are_anagrams function.

6. The final print statement uses an f-string to format the output, showing that "listen" and "silent" are anagrams, which is indicated by True.

Comments