Created
March 22, 2013 19:42
-
-
Save icework/5224149 to your computer and use it in GitHub Desktop.
anagram
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
input_file = open('wordsEn.txt') #read the english word list from file | |
data = [] | |
for line in input_file: | |
line = line.rstrip('\n') #ignore the '\n' in the file | |
line = line.rstrip('\r') | |
if len(line)>=5 and len(line)<=7: | |
#print line | |
data.append(line) | |
def check(word, otherword): | |
word = word.lower() | |
otherword = otherword.lower() # convert the word to lowercase | |
checkLetter = [0]*26 # an list contain the number of letter show in the anagrm | |
uniqueLetter1 = 0 # the number of unique letter | |
for letter in word: # Iterate the anagram | |
if checkLetter[ord(letter)-97] == 0: | |
uniqueLetter1+=1 # count the unique letter | |
checkLetter[ord(letter)-97] += 1 # log the frequency of each letter | |
for letter in otherword: #Iterate the correct word | |
if checkLetter[ord(letter)-97] == 0: | |
return False #If the correct word contain the letter the anagram doesn't have retuen false | |
else: | |
checkLetter[ord(letter)-97] -= 1 | |
if checkLetter[ord(letter)-97] == 0: | |
uniqueLetter1 -= 1 | |
if uniqueLetter1 == 0: | |
return True | |
else: | |
return False | |
def findWord(word, diction): # Iterate the list, find a correct word of the anagram | |
for enWord in diction: | |
if check(word, enWord): | |
return enWord | |
return False | |
def test(): | |
if not (findWord("pplea", data) == "apple"): | |
print "Test not pass!" | |
return | |
if not (findWord("ythitr", data) == "thirty"): | |
print "Test not pass!" | |
return | |
print "Test pass!" | |
test() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment