Check Anagrams in Python
Anagrams become comparable after normalization and sorting.
What is Check Anagrams?
Anagrams become comparable after normalization and sorting.
Check whether two texts contain the same letters.
When should you use it?
- Learn Python syntax through a practical example.
- Build a foundation for larger programming problems.
- Test an idea quickly without a local setup.
Example code
main.py
def normalize(text):
# Ignore spaces, punctuation, and letter case.
return sorted(character.lower() for character in text if character.isalpha())
first, second = "listen", "silent"
result = "are" if normalize(first) == normalize(second) else "are not"
print(f"{first} and {second} {result} anagrams")
Expected output
listen and silent are anagrams
How it works
The helper removes nonletters, lowercases the remaining characters, and sorts them.
Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.
Practice exercises
Modify the runnable example with the exercises below to build understanding beyond copying the result.
- Change the input and predict the output before running.
- Handle empty or invalid input.
- Wrap the logic in a function and add more test cases.