简体   繁体   中英

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

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]))  

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

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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM