Home > Software design >  is this a good approach for anagram problem?
is this a good approach for anagram problem?

Time:10-16

Hello everyone i am beginner and i wanted to ask is this a good approach to not sort characters in (is anagram) problem i saw some tutorials and they sorted the strings but i wrote an algorithm without sorting the string and it works very well on the goal.

def is_anagram(str1, str2):
    if len(str1) != len(str2):
        return False
    else:
        for i in range(len(str2)):
            if str1[i] not in str2 or str2[i] not in str1:
                return False
        return True

    return False


print(is_anagram("hey", "hey"))

it is very simple than tutorials and as i checked its running time was 1 sec on about two million length of string.

Thank You need your consideration.

CodePudding user response:

Try this:

from collections import Counter

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

Examples:

>>> is_anagram("pat", "tap")
True
>>> is_anagram("hell", "heel")
False
>>> 

If you want to write it completely on your own, you can create a dict for each string, where the keys are the individual characters and the values are the number of occurrences of that character. Then compare dicts.

  • Related