how to iterate through each set

Cameron Walsh cameron.walsh at gmail.com
Sun Nov 4 01:18:03 EDT 2007


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.



More information about the Python-list mailing list