Home > OS >  check for anagram in pair of input given as phrase = A, B. where A and B are 2 words
check for anagram in pair of input given as phrase = A, B. where A and B are 2 words

Time:11-17

this is the code I wrote. but it gives True/False for each alphabet. I want the output to give me a single true or false. what changes should I make?

Z = input()
Y = Z.split()
M = list(Y[0])
N = list(Y[1])

M.pop(-1)

for i in range(len(N)):
    print(M.count(M[i]) == N.count(N[i]))  

CodePudding user response:

I would take another approach. If you sort the letters of both words and compare them against each other, then you will get a single True if the words are anagrams of each other:

>>> def is_anagram(word1, word2):
...   return sorted(word1) == sorted(word2)
>>> is_anagram('elbow', 'below')
>>> True
>>> is_anagram('elbow', 'lower')
>>> False

CodePudding user response:

Check my code:

A = "a decimal point".replace(" ","")
B = "i m a dot in place".replace(" ","")


def checkAnagram(A,B):
    for i in range(len(A)):
        
        if(A.count(A[i])!=B.count(A[i])):
            return False
    return True

         
if(len(A)!=len(B)):
        print("Pair is not anagram.")
else:
    if(checkAnagram(A,B)):
        print("pair is anagram")
    else:
        print("Pair is not Anagram")
  • Related