Search code examples
pythonanagram

My anagram code doesn't account for multiple letters


So my code gets two words, and checks if one is the anagram of another one.

However doesn't work if multiple letters are exchanged, although I tried to account for that.

storedword = input("Enter your primary word \t")
global word 
word = list(storedword)


word3 = input("Enter anagram word \t")
word3lowercase = word3.lower()
anaw = list(word3lowercase)


counter = int(0)
letterchecker = int(0)
listlength = len(word)
newcounter = int(0)
if len(anaw) != len(word):
    print ("not anagram")

if len(anaw) == len(word):
    while counter < listlength and newcounter < listlength:
        tempcount = 0
        if anaw[counter] == word[newcounter]:
            temp = word[newcounter]
            word[newcounter] = word[tempcount]
            word[tempcount]=temp
            letterchecker +=1
            counter +=1
            tempcount +=1
            newcounter = int(0)

        else:
            newcounter +=1

if counter == len(word):
    print ("anagram")
else:
    print ("not anagram")

I think it's gone somewhere wrong after the if len(anaw) section, for example if the primary word is "hannah", and the secondary word is "hannnn", it thinks it's an anagram.


Solution

  • newcounter = int(0)
    

    This is the line that causes the trouble (in the while loop). Because of it you start checking the word from the beginning again. I think you want it to be newcounter=letterchecker. Since already used characters are put to the front of word they are ignored if you start with letterchecker

    Tell me if it works

    Edit:Checked with example given, seems to work.