Anagrams Within Words in Python

I implemented the Anagrams Within Words programming puzzle from Programming Praxis in Python, a language I haven’t used since my college days when I used it to  implement a REST service as part of my final year project.

Needless to say, I had forgotten most of the syntax and had to repeatedly refer to the Python docs.

Problem Statement
Given two words, determine if the first word, or any anagram of it, appears in consecutive characters of the second word. For instance, cat appears as an anagram in the first three letters of actor, but car does not appear as an anagram in actor even though all the letters of car appear in actor.

Solution

class AnagramChecker:
    #Temporary list that contains the first word. We will remove matching
    #characters from here
    #Python doesn't insist on explicit declaration of class variables but
    #this variable was declared for purposes of clarity
    tempFirstWord = []

    def checkChar(self, charOfSecondWord):
        if charOfSecondWord in self.tempFirstWord:
            #Remove matching character from temporary first word
            self.tempFirstWord.remove(charOfSecondWord)
        else:
            #Reset first word as we need to start checking from beginning
            self.tempFirstWord = list(self.firstWord)

        #If our tracking variable runs down to 0 then we have a complete and continuous match
        if len(self.tempFirstWord) == 0:
            return True
        else:
            return False

    def checkAnagram(self, userInput):
        #Python's wonderful list unpacking feature means we don't need a temporary
        #variable to store the split results
        self.firstWord, self.secondWord = userInput.split(" ")

        self.tempFirstWord = list(self.firstWord)

        anagramFound = False
        for c in self.secondWord:
            if self.checkChar(c):
                anagramFound = True
                break

        return anagramFound

userInput = raw_input("Please enter two words: ")

checkerObj = AnagramChecker()
print "Anagram found: ", checkerObj.checkAnagram(userInput)

Also here on GitHub Gists.

Sample use

Please enter two words: act tractor
Anagram found:  True

Please enter two words: car actor
Anagram found:  False

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s