Program to Check Anagram in Python | Example

Program to Check Anagram in Python | Example

What is Anagram?

Tow strings are anagrams if they have the same set of characters. In other words, two strings are anagrams if we can form one string by rearranging elements in another string.

Let’s take an example.

  • Strings “secure” and “rescue” are anagrams.
  • String “listen” and “silent” are anagrams.

Characteristics of Anagram:

  • Two string are not anagrams if they have different length.
  • If we sort the two anagram strings, they should be equal.

These are nothing but the conditions we are going to consider in our algorithm and program.

Python Program

Write a Program to Check Anagram in Python.

(This question has been asked in many coding interviews. Check interview coding questions.)

There are multiple ways to solve this problem. You can solve it by using sorting or by using for loop.

Here we are using a sorting mechanism.

def test_anagram(str_a, str_b):
	if not len(str_a) == len(str_b):
		print(f"'{str_a}' & '{str_b}' are not anagrams as they have different lengths.")
		return False

	if sorted(str_a) == sorted(str_b):
		print(f"'{str_a}' & '{str_b}' are anagrams.")
		return True
	else:
		print(f"'{str_a}' & '{str_b}' are not anagrams.")
		return False


print(test_anagram("abc", "ba"))
print(test_anagram("abc", "abb"))
print(test_anagram("cba", "bca"))

Output:

'abc' & 'ba' are not anagrams as they have different lengths.
False
'abc' & 'abb' are not anagrams.
False
'cba' & 'bca' are anagrams.
True

We are considering three different use cases by calling the test_anagram function with different strings.

Note: In the above code, we are using the sorted() inbuilt function to sort the given string. Check the difference between sort() and sorted() in Python.

If you want to implement an anagram check program in C, you have to write more than 50 lines of code. Python makes your job easy where you can use inbuilt Python functions and don’t need to write from the scratch unlike C/C++ and Java programming.

Leave a Reply

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