[Tutor] Finding palindromes in a list

Dave Angel d at davea.name
Sat Jun 9 04:03:45 CEST 2012

On 06/08/2012 09:46 PM, Mike Nickey wrote:
> Thanks guys,
You top-posted your comments, so we lose all context.  Put your remarks
after the part you're quoting.  Or if the stuff you're quoting is
irrelevant, strip it out, as I've done here.  It's irrelevant because
the order is wrong.

> Those have helped. Now a new issue comes up. The list 'palindrome' is
> not being populated.  I know that there is a few in the list.  I think
> this is in the compareElements def. While I'm familiar with the
> .append() call I don't know why it's not populating the palindrome
> list.
> Thanks again for all the assistance.

Where's a sample input?  What's the file supposed to look like? One word
per line, or multiple ones?

> def getFile():
>     fname = raw_input('Enter location and filename: ')
>     print
> #attempt the open the file for reading
>     try:
>         fobj = open(fname, 'r')
>     except IOError, e:
>         print "*** file open error:", e
>     else:
>     #display contents to the screen
>         for eachLine in fobj:
>             # create list here
>             eachLine.strip().split()

Why don't you do something with the results of these operations.  As
they stand, they do nothing useful.

>             wordList.append(eachLine)

So wordList is a list of the raw lines from the file, complete with
newline on each line.  If that's what you want, call it linelist.

>         fobj.close()
> def compareElements(wordList):
>     for item in wordList:
>         if item == item[::-1]:          #wordList[item] ==
> wordList[item].reverse():
>             print item
>             palindromes.append(item)
> wordList = []
> palindromes = []
> getFile()
> print "\nPrinting new Word list!!!"
> print wordList[:]

Did this display what you wanted?  If not, fix that before trying to
figure out the compareElements part.  Hint, you probably wanted WORDs in
your wordlist, not lines.

> print "\nComparing Word List!!!"
> compareElements(wordList)
> print "\nPrinting palindromes"
> print palindromes[:]
> print "\nDone!!!"



More information about the Tutor mailing list