Gasoline Mileage Log
November 2, 2012
I keep a log of gasoline mileage on a 3-by-5 card in the glovebox of my car. Recent entries on the card look like this:
Date Mileage Miles Gals MPG
---------- ------ ----- ---- --
08/18/2012 107679 290.8 13.1 22
08/26/2012 107934 255.3 10.4 24
09/05/2012 108197 262.9 12.2 22
09/16/2012 108518 321.7 13.8 23
10/02/2012 108762 243.5 12.2 20
10/09/2012 109028 265.6 11.5 24
10/18/2012 109306 278.1 12.4 22
10/27/2012 109589 283.3 11.1 26
Your task is to read a file containing mileage and gallons, compute miles per gallon, and produce an output similar to that shown above. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.
[…] today’s Programming Praxis exercise, our goal is to calculate and show the gas mileage given an input file […]
My Haskell solution (see http://bonsaicode.wordpress.com/2012/11/02/programming-praxis-gasoline-mileage-log/ for a version with comments):
import Text.Printf import Text.XFormat.Read line :: String -> (Float, Float) line s = (m,g) where Just (m,_,g) = readf (Float, Space, Float) s showLog :: [(Float, Float)] -> [String] showLog es = "Miles Gals Avg" : "------ ---- ----" : zipWith (\(m2,g) (m1,_) -> printf "%.0f %.1f %.1f" m2 g ((m2 - m1) / g)) (tail es) es main :: IO () main = mapM_ putStrLn . showLog . map line . lines =<< readFile "input.txt"My Python solution.
print "{0:s}".format("Miles Gals Avg\n----- ---- ----") oldmiles = None for line in open("mileage.txt"): miles, gals = [float(e) for e in line.split()] if oldmiles: avg = (miles - oldmiles) / (gals) print "{0:6.0f} {1:3.1f} {2:3.1f}".format(miles, gals, avg) oldmiles = miles[…] Pages: 1 2 […]