-->

Python 2.5.1.8 LAB: Anagrams

 Anagrams

Anagram Listen = Silent

[1] An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.[1] For example, the word binary into brainy and the word adobe into abode. The original word or phrase is known as the subject of the anagram. Any word or phrase that exactly reproduces the letters in another order is an anagram.

Now, lets see the lab question.

Scenario

An anagram is a new word formed by rearranging the letters of a word, using all the original letters exactly once. For example, the phrases "rail safety" and "fairy tales" are anagrams, while "I am" and "You are" are not.

Your task is to write a program which:

  • asks the user for two separate texts;
  • checks whether, the entered texts are anagrams and prints the result.

Note:

  • assume that two empty strings are not anagrams;
  • treat upper- and lower-case letters as equal;
  • spaces are not taken into account during the check - treat them as non-existent

Test your code using the data we've provided.

Test data

Sample input:

  • Listen
  • Silent

Sample output:

Anagrams

Sample input:

  • modern
  • norman

Sample output:

Not anagrams

Solution Code:

def check(s1, s2):
    s1 = s1.replace(" ", "")
    s2 =  s2.replace(" ", "")

    if(sorted(s1.lower()) == sorted(s2.lower())):
        print("The strings are anagrams.")
    else:
        print("The strings aren't anagrams.")        

s1 = input("Please Enter the First String: ")
s2 = input("Please Enter the Second String: ")
check(s1, s2)

Can you come up with a shorter / better solution? Please mention it in the comments 👀

Remember "Learn Less, Practice More"





References

1. Wikipedia contributors. (2022, February 1). Anagram. Wikipedia. Retrieved February 5, 2022, from https://en.wikipedia.org/wiki/Anagram

Post a Comment

0 Comments