Introductory Programming
Fall 2004
Homework 11
The reading for this assignment is Chapter 13
of How to think....
- Using the Time class from Chapter 13 as a template,
write a program named Date.py that defines a Date
class and then
- 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.
- 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.
- 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.
- 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:
- Start with a list of month names, like:
names = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug',
'Sep', 'Oct', 'Nov', 'Dec' ]
- Create a dictionary that maps from the name of each month
to the number of days in the month.
- Create a list that contains the number of days in each month.
- 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].
- Apply cumsum to your list of month lengths and store the
result in a list called cumulative_days.
- 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.
|