Created
November 1, 2022 16:59
-
-
Save ragnarok22/eeed5f73ef5ba14578d90c8472371b64 to your computer and use it in GitHub Desktop.
Determine if two words are anagrams
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def is_anagram(word1: str, word2: str) -> bool: | |
"""Determine if two words are anagram | |
:param word1: word to check if is an anagram | |
:param word2: word to check if is an anagram | |
:return: True whether the words are anagram or False otherwise | |
""" | |
if word1 == word2: | |
return True | |
elif len(word1) != len(word2): | |
return False | |
else: | |
for i in word2: | |
count = word1.count(i) | |
if count == 0 or count != word2.count(i): | |
return False | |
return True |
leynier
commented
Nov 1, 2022
def is_anagram(word1: str, word2: str) -> bool:
if len(word1) != len(word2):
return False
if word1 == word2:
return True
data: dict[str, int] = {}
for c in word1:
try:
data[c] += 1
except KeyError:
data[c] = 1
for c in word2:
t = data.get(c, 0)
if not t:
return False
data[c] = t - 1
return all(not data[c] for c in data)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment