DEV Community

Cover image for Python challenge_7
Mahmoud EL-kariouny
Mahmoud EL-kariouny

Posted on

 

Python challenge_7

Anagrams

level of challenge 3/10

  • Two strings are anagrams
  • if you can make one from the other by rearranging the letters.
  • Write a function
  • named is_anagram that takes two strings as its parameters.
  • Your function should return True if the strings are anagrams,
  • and False otherwise.

  • For example,

  • the call is_anagram("typhoon", "opython") should return True while the call

  • is_anagram("Alice", "Bob") should return False.

Hint

  • You can compare how many times each letter appears in each string.
  • Alternatively, sorting the letters in each string makes this much easier.
My solution
def is_anagram(string_one, string_two):
    str_dic_one = {}
    str_dic_tow = {}

    for str_one in string_one:
        if str_one in str_dic_one:
            str_dic_one[str_one] += 1
        else:
            str_dic_one[str_one] = 1

    for str_tow in string_two:
        if str_tow in str_dic_tow:
            str_dic_tow[str_tow] += 1
        else:
            str_dic_tow[str_tow] = 1

    if str_dic_one == str_dic_tow:
        return True
    else:
        return False

print(is_anagram('typhoon', 'opython'))
Enter fullscreen mode Exit fullscreen mode
Another solution
def is_anagram(string1, string2):
    return sorted(string1) == sorted(string2)
Enter fullscreen mode Exit fullscreen mode
def count_letters(string):
    return {l: string.count(l) for l in string}
Enter fullscreen mode Exit fullscreen mode
def is_anagram(string1, string2):
    return count_letters(string1) == count_letters(string2)
Enter fullscreen mode Exit fullscreen mode

Add your solution in the comment :)

Top comments (3)

Collapse
 
tonytranrp profile image
Thanh Tran
def is_anagram(word1,word2):
    if sorted(word1)== sorted(word2):
        return True
    else:
        return False
Enter fullscreen mode Exit fullscreen mode
Collapse
 
tonytranrp profile image
Thanh Tran

def is_anagram(word1,word2):
if sorted(word1)== sorted(word2):
return True
else:
return False

Collapse
 
totally_chase profile image
Phantz • Edited
from collections import Counter

is_anagram = lambda x, y: Counter(x) == Counter(y)
Enter fullscreen mode Exit fullscreen mode

I'm gonna guess Counter would be able to do it pretty fast, if not the fastest.

An Animated Guide to Node.js Event Loop

Node.js doesn’t stop from running other operations because of Libuv, a C++ library responsible for the event loop and asynchronously handling tasks such as network requests, DNS resolution, file system operations, data encryption, etc.

What happens under the hood when Node.js works on tasks such as database queries? We will explore it by following this piece of code step by step.