Suppose we record in a file the following information for each leg of a car trip
ID: 3565248 • Letter: S
Question
Suppose we record in a file the following information for each leg of a car trip:
number of miles traveled amount of gas used
Write a program that gets the name of the file in which the above information is stored and after reading in the entire file, prints the gas mileage for each leg and the average mileage for the entire trip.
Suppose the file td1.txt contains the following data.
100 2
50 2
200 10
Here is a sample interaction.
Enter file name: td1.txt
Leg 1 50.0
Leg 2 25.0
Leg 3 20.0
Overall mileage 25.0
1) The information must be printed only after the entire data has been read in. (This was already specified.)
2) The file may be empty.
3) You must use while loops.
I suggest that you store the mileage information in a list. If mylist is a list, mylist.append(element) adds element to the list. len(mylist) returns the number of elements in mylist and mylist[-1] returns the last element in mylist.
Explanation / Answer
fname = raw_input("Enter Filename:")
f = open(fname,"r")
k = f.readlines()
if(len(k) = 0)
exit(1)
l = []
for x in k:
l.append(x.split())
miles = 0
gas = 0
n=0
i = 0
while(i<len(l)):
n = n+1
p = l[i]
milleg = float(p[0])/float(p[1])
print "leg",n ,milleg
finalmiles = finalmiles+int(p[0])
finalgas = finalgas+int(p[1])
i =i+1
avgmilage = float(miles/gas)
print "overall milage",avgmilage
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.