how to iterate through each set

Tom_chicollegeboy tbabula at gmail.com
Sun Nov 4 01:54:19 EDT 2007


On Nov 4, 12:18 am, Cameron Walsh <cameron.wa... at gmail.com> wrote:
> 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.- Hide quoted text -
>
> - Show quoted text -

thanks. Python actually allows to replace its built-in functions with
code defined by user inside line. I do not think list() is one of they
keyword like if or while. For example, that can be done with
reverse().

The answer what I am looking is how to make python continue to go to
next block until -1.  I am not asking for code, only what algorithm
should do. But thank you anyway.




More information about the Python-list mailing list