Created
March 1, 2014 06:57
-
-
Save regularcoder/9286276 to your computer and use it in GitHub Desktop.
Anagrams Within Words in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#http://regularcoder.wordpress.com/2014/03/01/python-anagrams-within-words/ | |
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment