[Tutor] problem with an anagram program
Alan Gauld
alan.gauld at btinternet.com
Mon Mar 9 10:23:06 CET 2009
"jessica cruz" <jessica06cruz at yahoo.com> wrote
> I just started learning python an I'm currently working on this
> program.
> The purpose of this program is to read a string of letters from user
> input and print out all the words which are anagrams of the input
> string.
Where you define an anagram to be a word that is in wordlist I assume?
> it says that there is an error "invalid syntax" but I can't figure
> out where.
Always send us the full error message, it usually tells us where
to look, which is easier than reading the full program!
> #this reads all of the words in the file into a list
> infile = open('/afs/cats/courses/cmps012a-cm/pa1/wordList.txt')
> wdcount = int(infile.readline()) #first item is count of all the
> words
You do not use this, why bother?
> word_list = infile.readlines()
> wordList = []
> # code that will be compared will be a histogram type code with
> frequency
> # characters
> def code(w):
> hist = []
> chars = list(w)
> chars.sort()
> for letter in chars:
> if not letter in hist: # when the letter is not already in
> hist,
> hist.extend([letter, str(w.count(letter))]) # its added
> to hist along with its freq.
> else:
> continue
> coding = "".join(hist) # then they are joined as one string
> return coding
> # new list is made with words in word_list followed by its code
> for word in word_list:
> wordList.append(word)
> wordList.append(code(word[:(len(word)-2)]))
word[:len(word)-2] could be written much more clearly as
word[:-2]
> while True:
> word1 = raw_input('Enter word:')
> word = word1.lower()
> sig = code(word)
> i = 1
> if sig in wordList:
> print "Anagrams:"
> while i <= len(wordList): # when the sig of the inputed word is in
> the word list,
> if sig == wordList[i]
This looks like the syntax error - no colon.
I stopped here.
I think there are easier ways to do this!
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/l2p/
More information about the Tutor
mailing list