Re: how to iterate through each set



Tom_chicollegeboy wrote:
<snip!>

Here is my code:

def speed():
infile = open('speed.in', 'r')
line = infile.readline()
read = int(line)
print line
i = 0
t0 = 0
v = 0

while i<read:
line = infile.readline()
list = line.split()
s = int(list[0])
t1 = int(list[1])
t = t1- t0
v += s*t
i+=1
t0 = t1
print v

It works only for first set. How should I implement another solution
that would move program to read next set? I think I should implement
nested while look, with first that reads until -1 and under it another
while loop that reads n times sets. But I have no idea how. Can you
help me?


Clues:

1.) Your program works for one block. As you suggested you now need to loop over some of your code until you reach an end condition.
2.) The end condition has been given to you already in the text and the file.
3.) This can be done with two more lines of code. One line to add a loop of some sort, checking for the end condition; and one line which brings you closer to the end condition after each block, and prepares you for the next block.

I hope this has given you enough to go on without confusing you or giving you the answer outright.

Now a few general pointers unrelated to your assignment:

1.) list is a keyword in python. Don't call your variables list.
2.) You've left the file open at the end of your program. Yes, Python will close it once the program has finished, but it's good practice to close it yourself as soon as you've finished with it. This won't be a problem in this assignment, but it may be in later assignments.
.



Relevant Pages

  • Re: Assignment in a while?
    ... can't do an assignment in the while loop. ... (see the commented out while loop), ... In the beginning of my python experience, I was a bit irritated at ... irritation really doesn't last very long. ...
    (comp.lang.python)
  • Re: how to iterate through each set
    ... loop over some of your code until you reach an end condition. ... Now a few general pointers unrelated to your assignment: ... list is a keyword in python. ...
    (comp.lang.python)
  • assignment in a for loop
    ... I understand that this is due to the fact that in Python ... what looks like "assignment" really is binding a name to an object. ... result is that inside the loop I am creating an object with value ... not using a list comprehension.) ...
    (comp.lang.python)
  • Can you introduce some book about python?
    ... appending key-value pairs to a dict (Peter ... Is Python suitable for a huge, ... >> to the list on each loop... ...
    (comp.lang.python)
  • Re: Am I the only one who would love these extentions? - Python 3.0 proposals (long)
    ... Why is it nice enough to make it be a syntax addition, ... to point an image viewer/editor at a chunk of Python code. ... You argue consistancy to other keywords. ... Why is this new loop construct of yours useful enough ...
    (comp.lang.python)