18. Anagrams
Two words are anagrams when one is the other's letters in a different order: listen and silent use the same six
letters. Phrases can be anagrams too, when only their letters count.
Write a function are_anagrams(a, b) that takes two strings and returns True if they are anagrams, or False if
they aren't:
- Only letters count. Spaces, punctuation and anything else that isn't a letter are left out.
- Ignore case:
Danddare the same letter. - Every letter must appear the same number of times in both:
aabandabare not anagrams. - Two strings with no letters at all, such as two empty strings, are anagrams.
Example 1
a = "listen", b = "silent"TrueExample 2
a = "Dormitory", b = "Dirty room!"TrueExample 3
a = "aab", b = "ab"FalseConstraints
aandbeach have 0 to 50 characters.- They are English letters, spaces and punctuation.
Submit also runs 12 more tests you can't see.
Practises String Methods (lesson 5).
- Clean both strings the same way: keep each character
chfor whichch.isalpha()isTrue(a letter), asch.lower(). Spaces, punctuation and capitals then don't count. - A set forgets how many times a letter appears:
set("aab") == set("ab")isTrue. Compare something that keeps the counts. sorted(letters)puts the letters in order, and two strings are anagrams exactly when their sorted letters are equal. Write the cleaning as a helper function and call it onaand onb; with no letters at all, both give[].
Solve it without hints for 3 stars, with hints for 2, after seeing the solution for 1.
One way to solve it, once you've had a go.
Solving it after seeing the solution earns 1 star.
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
def are_anagrams(a, b):
"""Check whether two strings are anagrams.
a, b: str, letters, spaces and punctuation; may be
empty
Returns: bool, True if they use the same letters the
same number of times, ignoring case and anything
that isn't a letter
"""
# Write your code here
pass
Run your code to see how it does on the test cases, or Submit to check every test.