Check if two Strings are Anagram in Python
def main():
"""
Prints if two strings are anagram.
"""
a = input("Enter string A: ")
b = input("Enter string B: ")
r = is_anagram(a, b)
print(r)
def is_anagram(a: str, b: str):
"""
Checks if two English words are anagram.
"""
a_counts = frequency(a)
b_counts = frequency(b)
return a_counts == b_counts
def frequency(text: str):
"""
Counts the frequency of English letter in a string.
"""
# Represent the frequency of 26 English letters in an array
counts = [0] * 26
# Count the occurrences of each lower cased English letter
for c in text:
c = c.lower()
if "a" <= c < "z":
counts[ord(c) - ord("a")] += 1
return counts
if __name__ == "__main__":
main()
def main():
"""
Prints if two strings ignoring spaces are anagram.
"""
a = input("Enter string A: ")
b = input("Enter string B: ")
r = is_anagram(a, b)
print(r)
def is_anagram(a: str, b: str):
"""
Checks if two Unicode strings are anagram.
"""
a_counts = frequency(a)
b_counts = frequency(b)
return a_counts == b_counts
def frequency(text: str):
"""
Counts the frequency of each character in a string ignoring spaces.
"""
# Represent the frequency of characters using dictionary
counts: dict[str, int] = dict()
# Count the occurrences of each character excluding spaces
for c in text:
if c.isspace():
continue
elif c not in counts:
counts[c] = 1
else:
counts[c] += 1
return dict(sorted(counts.items()))
if __name__ == "__main__":
main()