[pythonvis] Re: exercise discussion

  • From: James Scholes <james@xxxxxxxxxxxxx>
  • To: pythonvis@xxxxxxxxxxxxx
  • Date: Sun, 18 May 2014 13:44:52 +0100

Ivan Pivac wrote:
> In exercise two regarding what time a walker returned home, I have the
> total time taken to walk the distance but don't know how to add those
> minutes onto the time of 6.52 am.
> 
> Would it be worth while, I wonder, if the experts on the list could
> actually code the exercises as we work through them so that we can
> discuss the tasks on the learning room forum?  there may be several ways
> of producing the answer so examining those methods would also be an
> invaluable learning experience.  Meanwhile, I'll continue working on the
> home arrival time.

I am by no means an expert, however, here is how I would solve that
problem.  This uses advanced topics (objects and importing packages)
which won't have been covered in the book yet, but hopefully the code
and comments is easy enough to follow.

For anybody wondering, the exercise reads as follows:
If I leave my house at 6:52 am and run 1 mile at an easy pace (8:15 per
mile), then 3 miles at tempo (7:12 per mile) and 1 mile at easy pace
again, what time do I get home for breakfast?

# CODE BEGINS HERE
import datetime

# Set a time format string which we'll use later
time_format = '%I:%M%p'

# Create a datetime object representing 6:52AM this morning
# (year, month, day, hour, minute
departure_time = datetime.datetime(2014, 5, 18, 6, 52)

# Create two timedelta objects, which store differences in time
# This way, we can easily add them together and get our answer
# First, 2 miles at 8 minutes 15 each
easy_miles = datetime.timedelta(minutes=8, seconds=15) * 2
# Then our 3 faster miles at 7 minutes 12
tempo_miles = datetime.timedelta(minutes=7, seconds=12) * 3

# Now, we add them all together
breakfast_time = departure_time + easy_miles + tempo_miles

# And print out the time, using our time format
print 'You will get home for breakfast at
{0}!'.format(breakfast_time.strftime(time_format))
# CODE ENDS HERE

If I run this file, I see the following:
C:\Users\jscholes\Dropbox\Dev\Python>python morning_run.py
You will get home for breakfast at 07:30AM!

I would imagine the author of the book had a much more
mathematical-based approach in mind, but this is an example of how
features provided by the language can help you.
-- 
James Scholes
http://twitter.com/JamesScholes

Other related posts: