Category Archives: Python

daysOld.py

I’m taking Udacity’s Intro to Computer Science and there was a good problem in Problem Set 2 (optional 2): Given your birthday and the current date, calculate your age in days. Account for leap days. Assume that the birthday and current date are correct dates (and no time travel).

All it gave you was the following procedure definition:

def daysBetweenDates(year1, month1, day1, year2, month2, day2):

The algorithm i used to solve my solution was:

Step 1: Figuring out the number of whole years have elapsed. Taking into account that if month2 was less than month1, you essentially have to borrow days from the prior year and subtract 1 from the value of year2-year1.

Step 2: Figuring out how many days have passed in the months not part of the full years. (Current date days are positive, and birth date days are negative. The sum of the two give the number of days elapsed outside of the full years.)

Step 3: Convert the years to days and add it all together including the extra days from leap years.

Here is the finished code from the primary procedure:


def daysBetweenDates(year1, month1, day1, year2, month2, day2):
    ##
    # Your code here.
    ##
    monthDays = 0

    fullYears = year2-year1
        if month2<month1:
        fullYears -= 1
        monthDays += 365

     monthDays = monthDays + daysFromMonths(month2) + day2 - daysFromMonths(month1) - day1

     daysOld = fullYears*365 + monthDays + leapDays(year1,month1,year2,month2)
     return daysOld

Step 1 was pretty straight forward and didn’t require an additional procedure for the calculation, but step 2 did. My aim was to be able to calculate the number of days have past in the year for any given month so that I could subtract the total days from date2 by the total days from date1 (excluding the days from full years).

That was accomplished by creating a procedure that was able to calculate the number of days in a year have passed up to a specified month. This procedure contained an array with the number of days in each month. When called, it looped through the array summing the days in every month until reaching the month parameter passed into the procedure.

The days from the full years were added to the days from the months and then finally the extra days for the leap years were added.

You can see my full solution on my Github account, here.

I ran into one speedbump because I assumed that leap years were all years divisible by 4. The last test case kept failing so I knew something was wrong. It turned out that my leap year assumption was wrong. From Wikipedia, it is actually:

if year is divisible by 400 then
   is_leap_year
else if year is divisible by 100 then
   not_leap_year
else if year is divisible by 4 then
   is_leap_year
else
   not_leap_year

Once i added a procedure that accounted for this, my solution was correct!