50 XP

18. Anagrams

Intermediate strings sorting

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: D and d are the same letter.
  • Every letter must appear the same number of times in both: aab and ab are not anagrams.
  • Two strings with no letters at all, such as two empty strings, are anagrams.

Example 1

Inputa = "listen", b = "silent"
OutputTrue
ExplanationBoth use e, i, l, n, s and t, once each.

Example 2

Inputa = "Dormitory", b = "Dirty room!"
OutputTrue
ExplanationThe space, the ! and capitals don't count.

Example 3

Inputa = "aab", b = "ab"
OutputFalse
Explanation"aab" has two a's but "ab" has only one.

Constraints

  • a and b each 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).

Code
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