π 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"
Anagramstr2 = "silent" if sorted(str1) == sorted(str2): print("Anagram") else: print("Not Anagram")
✅ Output
π 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"
print("Not Anagram")
Output
Anagramπ This method compares the frequency of each character.
πΉ Method 4 – Using Function
Truedef is_anagram(str1, str2): return sorted(str1.lower()) == sorted(str2.lower()) print(is_anagram("listen", "silent"))
✅ Output
π 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