Re: how to iterate through each set
- From: Cameron Walsh <cameron.walsh@xxxxxxxxx>
- Date: Sun, 04 Nov 2007 16:18:03 +1100
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.
.
- Follow-Ups:
- Re: how to iterate through each set
- From: Tom_chicollegeboy
- Re: how to iterate through each set
- References:
- how to iterate through each set
- From: Tom_chicollegeboy
- how to iterate through each set
- Prev by Date: how to iterate through each set
- Next by Date: Re: how to iterate through each set
- Previous by thread: how to iterate through each set
- Next by thread: Re: how to iterate through each set
- Index(es):
Relevant Pages
|