newbie - infinite loop
Mike C. Fletcher
mcfletch at home.com
Mon Mar 19 10:27:51 EST 2001
Your algo is:
for each element in uniqueList:
if the element equals the line:
add the line to the list
for goes over the list in order, and you're adding a new element, you'll
find that the list grows each time. Try printing uniqueList on each
iteration to see what you get. What you probably want is:
for line in file.readlines():
if line not in uniqueList: # note the "not"
uniqueList.append( line )
That's not going to be fast, but is the algo you seem to describe.
Enjoy,
Mike
-----Original Message-----
From: Paul Brian [mailto:pbrian at demon.net]
Sent: Monday, March 19, 2001 9:39 AM
To: python-list at python.org
Subject: newbie - infinite loop
All,
I have solved the opriginal problem but am left with a serious question.
Before I discovered the keywords in and not in, I tried to count unique
instances of names in a file.
I devcided to create a (neaarly) empty list, compare each name in the file
with that list. If the name was not in, append to list, otherwise leave it
alone.
After the following was run (and crashed) a couple of times I started using
my brain and realised there must be some "in" operator. However the problem
still stands - a for condition seems completely mutable.
So, line 3 sets a condition, 4 compares "q" to "q" and (wrongly for my
needs) adds "q" to the end of the list.
But then it seems that line 3 realises it has another element in its list
and goes back and compares
the newly appended "q" to my lineand so on ad infinitum (I have to kill the
process each time) !
Surely this should not happen. Surely the line 3 condition "for every
element in this list", should not constantly expand but should be set solid
till the next pass?
What have I done wrong - is it the mutable list v the immutable tuple
problem (but it should work..surely?) Or is this just the way things are -
"live with it and do not try anything like this again?"
thanks in advance
==============
uniqueList = ['q'] # create an nearl empyty list (seems to
ignore line 3 if truly empty)
line = 'q' # fake the retrieval of line from file
for listElement in uniqueList: #3
if listElement == line: #4
uniqueList.append(line) #5 at this point it seems to
think that there is now another list
#element to compare
and so loops for ever...help!
print len(uniqueList)
==============
--
http://mail.python.org/mailman/listinfo/python-list
More information about the Python-list
mailing list