how to iterate through each set

  • Thread starter Tom_chicollegeboy
  • Start date
T

Tom_chicollegeboy

I am begginer in learning Python language.

My assignment is to iterate through each set and display results. this
is text of assignment:

Bill and Ted are taking a road trip. But the odometer in their car is
broken, so they don't know how many miles they have driven.
Fortunately, Bill has a working stopwatch, so they can record their
speed and the total time they have driven. Unfortunately, their record
keeping strategy is a little odd, so they need help computing the
total distance driven. You are to write a program to do this
computation:

Speed in miles per hour Total elapsed time in hours

20 2

30 6

10 7

this means they drove 2 hours at 20 miles per hour, then 6-2=4 hours
at 30 miles per hour, then 7-6=1 hour at 10 miles per hour. The
distance driven is then (2)(20) + (4)(30) + (1)(10) = 40 + 120 + 10 =
170 miles. Note that the total elapsed time is always since the
beginning of the trip, not since the previous entry in their log.
You will implement a function speed in module speed.py that will help
Bill and Ted compute the distance they traveled on several road trips.


The input will come from file speed.in and consists of one or more
data sets where each data set represents a separate road trip. Each
set starts with a line containing an integer n, 1 ≤ n ≤ 10, followed
by n pairs of values, one pair per line. The first value in a pair, s,
is the speed in miles per hour and the second value, t, is the total
elapsed time. Both s and t are integers, 1 ≤ s ≤ 90 and 1 ≤ t ≤ 12.
The values for t are always in strictly increasing order. A value of
-1 for n signals the end of the input.

For each input set, output on the screen the distance driven, followed
by a space, followed by the word "miles". The output for input file
speed.in should be:



170 miles
180 miles
90 miles

this is speed.in file used for input:
3
20 2
30 6
10 7
2
60 1
30 5
-1

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?
 
C

Cameron Walsh

Tom_chicollegeboy said:
<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.
 
D

Dennis Lee Bieber

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?

Homework, huh? So I need to avoid a working solution...

Personally, based upon the nature of the data file, I'd base the
entire algorithm on a control break which is signified by a line with a
single "term", and ignore the "count" value of that term.

I'd have to ignore the first "control break" as there is no output
at that time. That can be done by initially setting the total mileage to
None (not to 0).

On a control break (len(input.split()) == 1): if total mileage is
NOT None, output results; set total mileage and elapsed time to 0.

On a data line (len(input.split()) == 2): total mileage = total
mileage + speed * (current time - elapsed time); elapsed time = current
time.

Exit on EOF.


This algorithm will function even with erroneous input:

4 <== only three actual values follow
20 2
30 6
10 7
2
60 1
30 5
-1


Calling the function "speed" is misleading too -- the /input/ is
speed and time, but the output wanted is mileage.

With the following data:
-=-=-=-=-=-=-=-
4
20 2
30 6
10 7
2
60 1
30 5
-1
10 1
25 1
5 10
-=-=-=-=-=-=-=-=-

A quick program produces the following output (NOTE: I added a LOT
of ouput statements so you can see the logic -- but I won't show the
actual code).

initialize total None, elapsed 0, trip count 0
open data file
loop over lines in input file, exit on null line
input line is: [4]
number of values in the line: 1
one value, control break
no trip data read before this control break
resetting total mileage 0, elapsed 0, incrementing trip count 1
input line is: [20, 2]
number of values in the line: 2
elapsed miles: 40
input line is: [30, 6]
number of values in the line: 2
elapsed miles: 160
input line is: [10, 7]
number of values in the line: 2
elapsed miles: 170
input line is: [2]
number of values in the line: 1
one value, control break
trip 1: 170 miles
resetting total mileage 0, elapsed 0, incrementing trip count 2
input line is: [60, 1]
number of values in the line: 2
elapsed miles: 60
input line is: [30, 5]
number of values in the line: 2
elapsed miles: 180
input line is: [-1]
number of values in the line: 1
one value, control break
trip 2: 180 miles
resetting total mileage 0, elapsed 0, incrementing trip count 3
input line is: [10, 1]
number of values in the line: 2
elapsed miles: 10
input line is: [25, 1]
number of values in the line: 2
elapsed miles: 10
input line is: [5, 10]
number of values in the line: 2
elapsed miles: 55
No terminating control break found
Unfinished trip is:
trip 3: 55 miles


By the way -- YOUR sample input data has ONLY TWO TRIPS -- so how
can the correct output be THREE trips?
--
Wulfraed Dennis Lee Bieber KD6MOG
(e-mail address removed) (e-mail address removed)
HTTP://wlfraed.home.netcom.com/
(Bestiaria Support Staff: (e-mail address removed))
HTTP://www.bestiaria.com/
 
T

Tom_chicollegeboy

Tom_chicollegeboy said:
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.
 
D

Dennis Lee Bieber

-1
10 1
25 1

Talking about bad data? Obviously that third line should have a
value greater than 1
5 10
-=-=-=-=-=-=-=-=-
resetting total mileage 0, elapsed 0, incrementing trip count 3
input line is: [10, 1]
number of values in the line: 2
elapsed miles: 10
input line is: [25, 1]

Obviously, if the first hour was at 10mph, and then a measurement
said 25 mph @ (1hr - 1hr => 0hr)...
number of values in the line: 2
elapsed miles: 10
input line is: [5, 10]
number of values in the line: 2
elapsed miles: 55
No terminating control break found
Unfinished trip is:
trip 3: 55 miles
--
Wulfraed Dennis Lee Bieber KD6MOG
(e-mail address removed) (e-mail address removed)
HTTP://wlfraed.home.netcom.com/
(Bestiaria Support Staff: (e-mail address removed))
HTTP://www.bestiaria.com/
 
T

Tom_chicollegeboy

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?

Homework, huh? So I need to avoid a working solution...

Personally, based upon the nature of the data file, I'd base the
entire algorithm on a control break which is signified by a line with a
single "term", and ignore the "count" value of that term.

I'd have to ignore the first "control break" as there is no output
at that time. That can be done by initially setting the total mileage to
None (not to 0).

On a control break (len(input.split()) == 1): if total mileage is
NOT None, output results; set total mileage and elapsed time to 0.

On a data line (len(input.split()) == 2): total mileage = total
mileage + speed * (current time - elapsed time); elapsed time = current
time.

Exit on EOF.

This algorithm will function even with erroneous input:

4 <== only three actual values follow
20 2
30 6
10 7
2
60 1
30 5
-1

Calling the function "speed" is misleading too -- the /input/ is
speed and time, but the output wanted is mileage.

With the following data:
-=-=-=-=-=-=-=-
4
20 2
30 6
10 7
2
60 1
30 5
-1
10 1
25 1
5 10
-=-=-=-=-=-=-=-=-

A quick program produces the following output (NOTE: I added a LOT
of ouput statements so you can see the logic -- but I won't show the
actual code).

initialize total None, elapsed 0, trip count 0
open data file
loop over lines in input file, exit on null line
input line is: [4]
number of values in the line: 1
one value, control break
no trip data read before this control break
resetting total mileage 0, elapsed 0, incrementing trip count 1
input line is: [20, 2]
number of values in the line: 2
elapsed miles: 40
input line is: [30, 6]
number of values in the line: 2
elapsed miles: 160
input line is: [10, 7]
number of values in the line: 2
elapsed miles: 170
input line is: [2]
number of values in the line: 1
one value, control break
trip 1: 170 miles
resetting total mileage 0, elapsed 0, incrementing trip count 2
input line is: [60, 1]
number of values in the line: 2
elapsed miles: 60
input line is: [30, 5]
number of values in the line: 2
elapsed miles: 180
input line is: [-1]
number of values in the line: 1
one value, control break
trip 2: 180 miles
resetting total mileage 0, elapsed 0, incrementing trip count 3
input line is: [10, 1]
number of values in the line: 2
elapsed miles: 10
input line is: [25, 1]
number of values in the line: 2
elapsed miles: 10
input line is: [5, 10]
number of values in the line: 2
elapsed miles: 55
No terminating control break found
Unfinished trip is:
trip 3: 55 miles

By the way -- YOUR sample input data has ONLY TWO TRIPS -- so how
can the correct output be THREE trips?
--
Wulfraed Dennis Lee Bieber KD6MOG
(e-mail address removed) (e-mail address removed)
HTTP://wlfraed.home.netcom.com/
(Bestiaria Support Staff: (e-mail address removed))
HTTP://www.bestiaria.com/

very helpful hints. thank you very much
 
T

Tom_chicollegeboy

I figured out problem. here is my code. now it works as it should!
Thank you everyone!

def speed():
infile = open('speed.in', 'r')
line = infile.readline()
read = int(line)
while '-1' not in line:
i = 0
t0 = 0
v = 0
if len(line.split())==1:
read = int(line)
while i<read:
line = infile.readline()
list1 = line.split()
s = int(list1[0])
t1 = int(list1[1])
t = t1- t0
v += s*t
i+=1
t0 = t1
print v
line = infile.readline()
infile.close()

speed()
 
C

Cameron Walsh

Tom_chicollegeboy said:
I figured out problem. here is my code. now it works as it should!
Thank you everyone!
I decided my 4th clue earlier was too much, so I removed it before
posting. It looks like you got it anyway =)

You've now solved it the way the course instructor intended you to solve
it. I would have done it this way:

def speed():
journeys = []
for line in open('speed.in', 'r').readlines():
line = list(int(i) for i in line.split())
if len(line) == 1:
if line[0] == -1:
break
time = 0
journeys.append(0)
else:
journeys[-1] += (line[1]-time) * line[0]
time = line[1]
for journey in journeys:
print journey

speed()
 
D

Dennis Lee Bieber

I figured out problem. here is my code. now it works as it should!
Thank you everyone!
Well, now if it works, it should be safe to show my version (with
all the print statements still in place)[watch out for line-wrapping]

-=-=-=-=-=-=-
DATA = "trips.dat"

print "\n\n"

total = None
trip = 0
elapsed = 0
print "initialize total %s, elapsed %s, trip count %s" % (total,
elapsed, trip)

print "open data file"
fin = open(DATA, "r")

print "loop over lines in input file, exit on null line"
for line in fin:
values = [int(x) for x in line.split()]
print "input line is: %s" % values
print "number of values in the line: %s" % len(values)
if len(values) == 1:
print "one value, control break"
if total:
print "trip %s: %s miles" % (trip, total)
else:
print "no trip data read before this control break"
total = 0
elapsed = 0
trip += 1
print "resetting total mileage %s, elapsed %s, incrementing trip
count %s" % (total, elapsed, trip)
else:
total += values[0] * (values[1] - elapsed)
elapsed = values[1]
print "elapsed miles: %s" % total

if total != 0:
print "No terminating control break found"
print "Unfinished trip is:"
print "trip %s: %s miles" % (trip, total)

fin.close()
-=-=-=-=-=-=-=-

I could strip 13 lines out of that to get the core requirements...
--
Wulfraed Dennis Lee Bieber KD6MOG
(e-mail address removed) (e-mail address removed)
HTTP://wlfraed.home.netcom.com/
(Bestiaria Support Staff: (e-mail address removed))
HTTP://www.bestiaria.com/
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top