Checking if two strings are anagrams in Python (Also for checking if a list has duplicates)

Python has two really nifty datatypes namely strings and lists that can handle a variety of tasks. For eg: if you want to check if two strings are anagrams.

Convert the string to lists, an iterable can be converted into list by list()

Sort both lists and simply check if they are equal.. Done !

To check if a list has duplicates, sorting the list comes handy again. We can simply sort the list and then check if consecutive elements are equal if so, we can directly say that we have duplicates! Easy wasn’t it? 🙂

An interesting method to do this I came across online was to make a letter histogram. Given two words, we want to determine if they are anagrams.. Lets make an int array of length 26(corresponding to each letter of the alphabet) all initialised to zero. Traverse through the first string, increment each corresponding integer variable, next traverse through the next list and go on decrementing the corresponding integer values.. If finally all elements are zero, we say we have anagrams, else we don’t.. Easy right? 🙂

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s