Check If Two Strings Are Anagram | Python 4 You | Lecture 202

Опубликовано: 13 Январь 2025
на канале: Rehan Blogger
14
0

To check if two strings are anagrams in Python, you can compare whether they have the same set of characters in the same frequency. An anagram is a word or phrase formed by rearranging the letters of another. Here's a common way to do it:

python code
def are_anagrams(str1, str2):
Remove spaces and convert to lowercase for case-insensitive comparison
str1 = str1.replace(" ", "").lower()
str2 = str2.replace(" ", "").lower()

Check if the lengths are the same
if len(str1) != len(str2):
return False

Create dictionaries to store character counts
char_count1 = {}
char_count2 = {}

Count characters in the first string
for char in str1:
if char in char_count1:
char_count1[char] += 1
else:
char_count1[char] = 1

Count characters in the second string
for char in str2:
if char in char_count2:
char_count2[char] += 1
else:
char_count2[char] = 1

Compare the dictionaries
return char_count1 == char_count2

Example usage
string1 = "listen"
string2 = "silent"
if are_anagrams(string1, string2):
print(f"'{string1}' and '{string2}' are anagrams.")
else:
print(f"'{string1}' and '{string2}' are not anagrams.")
In this code, the are_anagrams function:

Removes spaces and converts both strings to lowercase to ensure a case-insensitive comparison.
Checks if the lengths of the two strings are the same. If they have different lengths, they cannot be anagrams.
Creates dictionaries to count the frequency of each character in both strings.
Compares the character count dictionaries. If they are the same, the strings are anagrams.
You can replace string1 and string2 with the strings you want to check for anagrams. This code will work for strings with or without spaces and is not case-sensitive.#python4 #pythontutorial #pythonprogramming #python3 #pythonforbeginners #pythonlectures #pythonprograms #pythonlatest #rehanblogger #python4you #pythonlatestversion #pythonlatestversion Learn python3.12.0 and latest version of python3.13. If you are searching for python3.13.0 lessons, you are at the right place as this course will be very helpful for python learners or python beginners.