def are_anagrams(sent_one,sent_two):
sent_one=sent_one.replace(" ","")
sent_one=sent_one.lower()
sent_two=sent_two.replace(" ","")
sent_two=sent_two.lower()
dict_of_one={}
dict_of_two={}
for one in sent_one:
if one not in dict_of_one:
dict_of_one.setdefault(one,1)
else:
dict_of_one[one]+=1
for second in sent_two:
if second not in dict_of_two:
dict_of_two.setdefault(second,1)
else:
dict_of_two[second]+=1
print(dict_of_one)
print(dict_of_two)
for k,v in dict_of_one.items():
if k in dict_of_two and dict_of_two[k]==v:
return True
else:
return False
print(are_anagrams("Elvis", "Lives"))
print(are_anagrams("Elvis", "Live Viles"))
print(are_anagrams("Eleven plus two", "Twelve plus one"))
print(are_anagrams("Hot Water","Worth Coffee"))
Hi, I want to check two dictionaries are the same or not. I tried to do the end of the code, but I couldn't do it. Could you show me a way to do it?
def are_anagrams(first_word, second_word):
first_word = first_word.lower()
second_word = second_word.lower()
first_word = first_word.replace(' ', '')
second_word = second_word.replace(' ', '')
letters = []
for char in first_word:
letters.append(char)
for char in second_word:
if char not in letters:
return False
letters.remove(char)
return len(letters) == 0
this is the second approach...
def are_anagrams(first_word, second_word):
first_word = first_word.lower()
second_word = second_word.lower()
first_word = first_word.replace(' ', '')
second_word = second_word.replace(' ', '')
first_word_list=list(first_word)
first_word_list.sort()
first_word="".join(first_word_list)
second_word_list=list(second_word)
second_word_list.sort()
second_word="".join(second_word_list)
if hash(second_word)==hash(first_word):
return True
return False
print(are_anagrams("Elvis", "Lives"))
print(are_anagrams("Elvis", "Live Viles"))
print(are_anagrams("Eleven plus two", "Twelve plus one"))
print(are_anagrams("Hot Water","Worth Coffee"))
the third approach to this code uses hash codes. I try to add more ways to solve it...