Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

is this a good approach for anagram problem?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading