Python 2.5.1.8 LAB: Anagrams

 Anagrams

Anagram Listen = Silent
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

Comments

Popular posts from this blog

فرصتك للدراسة في ألمانيا: منحة ممولة بالكامل لطلاب الدراسات العليا

How to Deactivate Screen Reader in Kali Linux

Murphy's Law: Expect the Unexpected

Python 3.2.1.14 LAB: Essentials of the while loop

7 Reasons Why You Need to Learn English

Data Analysis Roadmap 2026: From Excel Lover to Python-Powered Analyst

15 Python Builtin-Functions You Need to Master as a Beginner

Prefixes vs Suffixes ? What are they?

Python 4.3.1.7 LAB: How many days: writing and using your own functions

Python 4.3.1.6 LAB: A leap year: writing your own functions