[Tutor] Finding palindromes in a list
Mike Nickey
mnickey at gmail.com
Sat Jun 9 03:46:57 CEST 2012
Thanks guys,
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.
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
eachLine.strip().split()
wordList.append(eachLine)
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[:]
print "\nComparing Word List!!!"
compareElements(wordList)
print "\nPrinting palindromes"
print palindromes[:]
print "\nDone!!!"
On Fri, Jun 8, 2012 at 6:38 PM, Dave Angel <d at davea.name> wrote:
> On 06/08/2012 09:01 PM, Marc Tompkins wrote:
>> On Fri, Jun 8, 2012 at 5:10 PM, Mike Nickey <mnickey at gmail.com> wrote:
>>
>>> def compareElements(wordList):
>>> for item in wordList():
>>> if item == item.reversed():
>>> print item
>>> else:
>>> next(item)
>>>
>>>
>> reversed() is not a string method. To reverse a string, try something like
>> this:
>>
>>> if item == item[::-1]
>>>
>>
>
>
> Also next(item) is useless and probably an error. You do not need an
> else clause there. the for loop takes care of those details.
>
>
>
> --
>
> DaveA
>
--
~MEN
More information about the Tutor
mailing list