How to check if two strings are anagram in Python

Question:

Given two strings s1 and s2, check if both the strings are anagrams of each other.
Examples: 

 

Input : s1 = "listen"
        s2 = "silent"
Output : The strings are anagrams.


Input : s1 = "dad"
        s2 = "bad"
Output : The strings aren't anagrams.

Solution:

Method #1 : Using sorted() function

Python provides a inbuilt function sorted() which does not modify the original string, but returns sorted string.
Below is the Python implementation of the above approach: 

Python

# function to check if two strings are
# anagram or not
def check(s1, s2):
	
	# the sorted strings are checked
	if(sorted(s1)== sorted(s2)):
		print("The strings are anagrams.")
	else:
		print("The strings aren't anagrams.")		
		
# driver code
s1 ="listen"
s2 ="silent"
check(s1, s2)

Output

The strings are anagrams.

Method #2 : Using Counter() function

  • Count all the frequencies of 1st string and 2 and using counter()
  • If they are equal then print anagram

 

# Python3 program for the above approach
from collections import Counter

# function to check if two strings are
# anagram or not
def check(s1, s2):

	# implementing counter function
	if(Counter(s1) == Counter(s2)):
		print("The strings are anagrams.")
	else:
		print("The strings aren't anagrams.")


# driver code
s1 = "listen"
s2 = "silent"
check(s1, s2)

Output

The strings are anagrams.

Method #3 : Using set() function

 

  • Check if the length of both string are same
  • Validate if both strings have same elements
  • For uniformity, convert the elements to lower()
  • Can also be used on integers in string

 

'''\
Python3 program for implementation of checking string is anagram or not
using set function.
'''

def check(s1, s2):

	# Asserting length of string
	assert len(s1) == len(s2), 'The strings are not of same length'
	
	# Implementation of set function
	if set(s1.lower()) == set(s2.lower()):
	print("The strings are anagrams.")
	else:
	print("The strings aren't anagrams.")
	
	# one liner for above implementation
	# print('The strings are anagrams.') if set(s1.lower()) == set(s2.lower()) else print('The strings aren\'t anagrams.')
	


#Driver code
if __name__ == '__main__':
	word1, word2 = 'listen', 'silent'
	check(word1, word2)

Output

The strings are anagrams.

 

Submit Your Programming Assignment Details