[Tutor] problem with an anagram program

Andre Engels andreengels at gmail.com
Mon Mar 9 09:40:36 CET 2009


Please next time, if possible, add the complete error message you get.
In this case, it tells us that the error is in this line:

             if sig == wordList[i]

You forgot the : at the end of this line (also, the next lines are not
indented extra, as they should).

On Mon, Mar 9, 2009 at 9:28 AM, 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. This is what
> I have and when I try to run the program it says that there is an error
> "invalid syntax" but I can't figure out where.
>
>
>
>
> #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
> 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)]))
>
>
> 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]
>             print wordList[i-1]  # the corresponding words are printed
>             i += 2 # then adds two because codes are every other entry
>     else:
>         print "No anagrams"
>     choice = raw_input("Continue? (yes/no)")
>     if choice == 'y' or choice == 'yes':
>         continue
>     else:
>         break




-- 
André Engels, andreengels at gmail.com


More information about the Tutor mailing list