LearnFrenzy
Sign in Take a free test

Strings · Strings Coding Problems · Question 2

Check whether two strings are anagrams in Python Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 2 Back to Exercise

For each pair of phrases, check whether they are anagrams, ignoring spaces and case.

Solution
main.py Run
def is_anagram(a, b):
    clean = lambda s: sorted(s.replace(" ", "").lower())
    return clean(a) == clean(b)

pairs = [("listen", "silent"), ("Dormitory", "Dirty room"), ("hello", "world")]
for a, b in pairs:
    print(f"{a!r} / {b!r}: {is_anagram(a, b)}")

Output Verified by running it on Python 3

'listen' / 'silent': True
'Dormitory' / 'Dirty room': True
'hello' / 'world': False

Two strings are anagrams when their sorted letters are equal. Removing spaces and lower-casing first makes the test fair.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links