Wednesday, 17 June 2026

πŸš€ Day 69/150 – Check Anagram in Python

 



πŸš€ Day 69/150 – Check Anagram in Python

An anagram means two strings contain the same characters in a different order.

✅ Example

listen → silent
race → care

Both words contain the same letters, so they are called anagrams.

πŸ”Ή Method 1 – Using  sorted()


str1 = "listen"

str2 = "silent" if sorted(str1) == sorted(str2): print("Anagram") else: print("Not Anagram")








✅ Output
Anagram

πŸ“Œ sorted() arranges characters alphabetically and compares both strings.

πŸ”Ή Method 2 – Taking User Input

str1 = input("Enter first string: ") str2 = input("Enter second string: ") if sorted(str1.lower()) == sorted(str2.lower()): print("Anagram") else: print("Not Anagram")








✅ Example Output
Enter first string: Heart
Enter second string: Earth

Anagram

πŸ“Œ lower() ignores uppercase and lowercase differences.


πŸ”Ή Method 3 – Using Dictionary Count

str1 = "race"

str2 = "care" count1 = {} count2 = {} for ch in str1: count1[ch] = count1.get(ch, 0) + 1 for ch in str2: count2[ch] = count2.get(ch, 0) + 1 if count1 == count2: print("Anagram") else: 






print("Not Anagram")

Output

Anagram

πŸ“Œ This method compares the frequency of each character.


πŸ”Ή Method 4 – Using Function

def is_anagram(str1, str2): return sorted(str1.lower()) == sorted(str2.lower()) print(is_anagram("listen", "silent"))





✅ Output
True

πŸ“Œ Functions make the code reusable and cleaner.


πŸ”₯ Key Takeaways

✅ Anagrams contain the same characters in different order
✅ sorted() is the easiest and most popular method
✅ Dictionary counting helps understand character frequency
✅ lower() avoids case mismatch problems
✅ Anagram problems are common in coding interviews

0 Comments:

Post a Comment

Popular Posts

Categories

100 Python Programs for Beginner (119) AI (282) Android (25) AngularJS (1) Api (7) Assembly Language (2) aws (30) Azure (11) BI (10) Books (262) Bootcamp (11) C (78) C# (12) C++ (83) cloud (1) Course (87) Coursera (300) Cybersecurity (31) data (6) Data Analysis (36) Data Analytics (23) data management (15) Data Science (370) Data Strucures (22) Deep Learning (178) Django (16) Downloads (3) edx (21) Engineering (15) Euron (30) Events (7) Excel (21) Finance (10) flask (4) flutter (1) FPL (17) Generative AI (73) Git (11) Google (53) Hadoop (3) HTML Quiz (1) HTML&CSS (48) IBM (42) IoT (3) IS (25) Java (99) Leet Code (4) Machine Learning (317) Meta (24) MICHIGAN (5) microsoft (13) Nvidia (8) Pandas (14) PHP (20) Projects (34) Python (1379) Python Coding Challenge (1162) Python Mathematics (1) Python Mistakes (51) Python Quiz (542) Python Tips (10) Questions (3) R (72) React (7) Scripting (3) security (4) Selenium Webdriver (4) Software (20) SQL (52) Udemy (18) UX Research (1) web application (11) Web development (9) web scraping (3)

Followers

Python Coding for Kids ( Free Demo for Everyone)