Checking strings against each other (Anagrams)

Why not just sort the strings?

>>> sorted('anagram')
['a', 'a', 'a', 'g', 'm', 'n', 'r']
>>> sorted('nagaram')
['a', 'a', 'a', 'g', 'm', 'n', 'r']
>>> sorted('anagram') == sorted('nagaram')
True

You can use the magic Counter from collections library. From documentation:

It is an unordered collection where elements are stored as dictionary keys and their counts are stored as dictionary values

So, you can initialize a Counter object with a string (a iterable) and compare with another Counter from a string

from collections import Counter

def is_anagram(str1, str2):
   return Counter(str1) == Counter(str2)

You need to think through your conditional logic a bit more. The loop is on the right track, but if there is a letter in s1 that is NOT in s2, you should break out of this loop and print the "False" statement. Consider using a variable like all_s1_in_s2 = True and then setting that to false if you find a letter that doesn't match.

Some other tips:

  • for l in s1 will loop through string s1 giving you access to each letter in sequence as l - you don't need range or len at all

  • The if .. in statement can help test whether a letter exists in a string, e.g. if letter in mystring: is a valid statement and this could help you a lot, again not needing range or len

  • You should avoid using numbers in variable names where possible - better would be word_one and word_two, as an example

Tags:

Python

Anagram