Introductory Programming
Fall 2004

Homework 11

The reading for this assignment is Chapter 13 of How to think....

Time and Date

  1. Using the Time class from Chapter 13 as a template, write a program named Date.py that defines a Date class and then

    1. Write a function named make_date that takes optional parameters named day, month, and year. It should create a Date object, store the parameters as attributes, and return the object.

      At this point you should test the program by writing code to invoke make_date and print the result. You should get some indication that you have created a Date instance, but by default Python doesn't print the attributes of the object.

    2. Write a function called print_date that takes a date as a parameter and that prints the date in some human-readable format.

      Test the program by creating a variable named today that contains today's date, and then print it.

  2. Write a function called days_since_2000 that takes a date and return the number of days since January 1, 2000. To keep it simple (for now), you can assume that all years have 365 days and all months have 30 days.

    As usual, test the new function.

  3. The next step is to compute the number of days per month correctly. There are a number of ways to do this, but I suggest the following steps:

    1. Start with a list of month names, like:

      names = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug',
      'Sep', 'Oct', 'Nov', 'Dec' ]
      

    2. Create a dictionary that maps from the name of each month to the number of days in the month.

    3. Create a list that contains the number of days in each month.

    4. Write a function called cumsum that takes a list of integers and returns a list that contains the cumulative sum. For example, the cumulative sum of [1, 2, 3, 4, 5] is [1, 3, 6, 10, 15].

    5. Apply cumsum to your list of month lengths and store the result in a list called cumulative_days.

    6. Modify days_since_2000 so that it uses cumulative_days to compute the number of days since the beginning of the year correctly. Be careful; it is tricky to get the indexing right. I believe that the correct answer for 2 December 2004 is 1795 days.