[Tutor] Finding palindromes in a list

Mike Nickey mnickey at gmail.com
Sat Jun 9 02:10:56 CEST 2012


I'm trying to write a bit of code that will run through a text file
and find the item or word string that is the same forward as it is
when it is revered...a palindrome. I'm having a bit of issue looping
through the wordList[] that I have created.

If you have any comments or suggestions I'd really appreciate the assistance.

Code:
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
            str(eachLine).strip().split()
            wordList.append(eachLine)
        fobj.close()

def compareElements(wordList):
    for item in wordList():
        if item == item.reversed():
            print item
        else:
            next(item)

wordList = []
getFile()
print
print "Printing new Word list!!!"
print wordList[:]
print "\nComparing Word List!!!"
compareElements(wordList)

-- 
~MEN


More information about the Tutor mailing list