Most python users would just use
sorted(string1) == sorted(string2). That's \$O(n log n)\$, which is not that much worse than your \$O(n)\$ solution.
But the code you've actually written is just a reimplementation of:
collections.Counter(string1) == collections.Counter(string2)
That said, your short-circuit if the lengths mismatch is a good idea no matter which implementation you use.
There are some style issues that jump out with your implementation:
char_count doesn't have a pressing need to be a nested function, I would put it at top level.
- Don't have a local variable named
char_count inside the same-named function.
- Don't cross numbers like
chr_count = char_count(string1);chr1_count = char_count(string2). If you need numbered variables, use the same number for all transformed forms also.
For your demonstration code, I would have written:
assert are_two_string_anagram("mary", "yram")
assert are_two_string_anagram("albert", "abelrt")
assert are_two_string_anagram("something", "anotherus")
for s1, s2 in [
assert are_two_string_anagram(s1, s2)
That way it can be run directly with
py.test (and possibly other harnesses, I know the standard
unittest requires wrapping them in a dummy class, but I haven't used any others).