Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Anagram test for two strings in python

This is the question:

Write a function named test_for_anagrams that receives two strings as parameters, both of which consist of alphabetic characters and returns True if the two strings are anagrams, False otherwise. Two strings are anagrams if one string can be constructed by rearranging the characters in the other string using all the characters in the original string exactly once. For example, the strings "Orchestra" and "Carthorse" are anagrams because each one can be constructed by rearranging the characters in the other one using all the characters in one of them exactly once. Note that capitalization does not matter here i.e. a lower case character can be considered the same as an upper case character.

My code:

def test_for_anagrams (str_1, str_2):
    str_1 = str_1.lower()
    str_2 = str_2.lower()
    print(len(str_1), len(str_2))
    count = 0
    if (len(str_1) != len(str_2)):
        return (False)
    else:
        for i in range(0, len(str_1)):
            for j in range(0, len(str_2)):
                if(str_1[i] == str_2[j]):
                    count += 1
        if (count == len(str_1)):
            return (True)
        else:
            return (False)


#Main Program
str_1 = input("Enter a string 1: ")
str_2 = input("Enter a string 2: ")
result = test_for_anagrams (str_1, str_2)
print (result)

The problem here is when I enter strings as Orchestra and Carthorse, it gives me result as False. Same for the strings The eyes and They see. Any help would be appreciated.

like image 344
Karan Thakkar Avatar asked Dec 17 '25 14:12

Karan Thakkar


1 Answers

I'm new to python, so excuse me if I'm wrong

I believe this can be done in a different approach: sort the given strings and then compare them.

def anagram(a, b):
  # string to list
  str1 = list(a.lower())
  str2 = list(b.lower())

  #sort list
  str1.sort()
  str2.sort()

  #join list back to string
  str1 = ''.join(str1)
  str2 = ''.join(str2)

  return str1 == str2

print(anagram('Orchestra', 'Carthorse'))
like image 91
LonelyCpp Avatar answered Dec 19 '25 06:12

LonelyCpp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!