Anagram test for two strings in python

Question:

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.

Asked By: Karan Thakkar

||

Answers:

The problem is that you just check whether any character matches exist in the strings and increment the counter then. You do not account for characters you already matched with another one. That’s why the following will also fail:

>>> test_for_anagrams('aa', 'aa')
False

Even if the string is equal (and as such also an anagram), you are matching the each a of the first string with each a of the other string, so you have a count of 4 resulting in a result of False.

What you should do in general is count every character occurrence and make sure that every character occurs as often in each string. You can count characters by using a collections.Counter object. You then just need to check whether the counts for each string are the same, which you can easily do by comparing the counter objects (which are just dictionaries):

from collections import Counter
def test_for_anagrams (str_1, str_2):
    c1 = Counter(str_1.lower())
    c2 = Counter(str_2.lower())
    return c1 == c2
>>> test_for_anagrams('Orchestra', 'Carthorse')
True
>>> test_for_anagrams('aa', 'aa')
True
>>> test_for_anagrams('bar', 'baz')
False
Answered By: poke

For completeness: If just importing Counter and be done with the exercise is not in the spirit of the exercise, you can just use plain dictionaries to count the letters.

def test_for_anagrams(str_1, str_2):
    counter1 = {}
    for c in str_1.lower():
        counter1[c] = counter1.get(c, 0) + 1
    counter2 = {}
    for c in str_2.lower():
        counter2[c] = counter2.get(c, 0) + 1

    # print statements so you can see what's going on,
    # comment out/remove at will
    print(counter1)
    print(counter2)

    return counter1 == counter2

Demo:

print(test_for_anagrams('The eyes', 'They see'))
print(test_for_anagrams('orchestra', 'carthorse'))
print(test_for_anagrams('orchestr', 'carthorse'))

Output:

{' ': 1, 'e': 3, 'h': 1, 's': 1, 't': 1, 'y': 1}
{' ': 1, 'e': 3, 'h': 1, 's': 1, 't': 1, 'y': 1}
True
{'a': 1, 'c': 1, 'e': 1, 'h': 1, 'o': 1, 's': 1, 'r': 2, 't': 1}
{'a': 1, 'c': 1, 'e': 1, 'h': 1, 'o': 1, 's': 1, 'r': 2, 't': 1}
True
{'c': 1, 'e': 1, 'h': 1, 'o': 1, 's': 1, 'r': 2, 't': 1}
{'a': 1, 'c': 1, 'e': 1, 'h': 1, 'o': 1, 's': 1, 'r': 2, 't': 1}
False
Answered By: timgeb

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'))
Answered By: LonelyCpp

Traverse through string test and validate weather character present in string test1 if present store the data in string value.
compare the length of value and length of test1 if equals return True Else False.

def anagram(test,test1):
    value =''
    for data in test:
        if data in test1:
            value +=  data
    if len(value) == len(test1):
        return True
    else:
        return False

anagram("abcd","adbc")
Answered By: Ravikumar Racha

def anagram(test,test1):
test_value = []
if len(test) == len(test1):
for i in test:
value = test.count(i) == test1.count(i)
test_value.append(value)
else:
test_value.append(False)

if False in test_value:
    return  False
else:
    return True

check for length of test and test1 , if length matches traverse through string test and compare the character count in both test and test1 strings if matches store the value in string.

Answered By: Ravikumar Racha

I have done Anagram Program in basic way and easy to understandable .

    def compare(str1,str2):
if((str1==None) or (str2==None)):
    print(" You don't enter string .")
elif(len(str1)!=len(str2)):
    print(" Strings entered is not Anagrams .")
elif(len(str1)==len(str2)):
    b=[]
    c=[]
    for i in str1:
        #print(i)
        b.append(i)
    b.sort()
    print(b)
    for j in str2:
        #print(j)
        c.append(j)
    c.sort()
    print(c)
    if (b==c and b!=[] ):
        print(" String entered is Anargama .")
    else:
        print(" String entered are not Anargama.")
else:
    print(" String entered is not Anargama .")
str1=input(" Enter the first String :")
str2=input(" Enter the second String :")

compare(str1,str2)
Answered By: sameer_nubia

A more concise and pythonic way to do it is using sorted & lower/upper keys.

You can first sort the strings and then use lower/ upper to make the case consistent for proper comparison as follows:

# Function definition
def test_for_anagrams (str_1, str_2):
    if sorted(str_1).lower() == sorted(str_2).lower():
        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)
Answered By: ParvBanks

Another solution:

def test_for_anagrams(my_string1, my_string2):
    s1,s2 = my_string1.lower(), my_string2.lower()
    count = 0
    if len(s1) != len(s2) :
        return False
    for char in s1 :
        if s2.count(char,0,len(s2)) == s1.count(char,0,len(s1)):
            count = count + 1
    return count == len(s1)
Answered By: Devanshi Ruparel

My solution is:

#anagrams

def is_anagram(a, b):
        if sorted(a) == sorted(b):
            return True
        else:
            return False

print(is_anagram("Alice", "Bob"))
Answered By: elnaz nasiri
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.