Friday the thirteenth is generally seen as an unlucky day in our culture. However, it is not immediately sure where this superstition comes from, and although there are numerous reports in various religions and customs, it seems that this superstition is at most 100 years old.

The combination of the weekday Friday and the number thirteen is also not as universal as you might think. In Belgium, the Netherlands and England, for example, Friday the thirteenth is indeed seen as an unlucky day. However, in Greece, Spain and Latin America, Tuesday the thirteenth is an unlucky day. In Italy everyone is extra careful on Friday the seventeenth.

Assignment

Write a function unlucky_days that takes a starting date (datetime.date). In addition, the function has three optional arguments that respectively indicate an end date (datetime.date), a day number (int) and a weekday number (int). The function must return the number of days (int) between the start and end date (including these boundaries) that fall on the specified weekday. If only the mandatory argument is given, the number of Fridays the thirteenth between the start date and today must be calculated. If the starting date comes later than the end date, there are no days between the starting date and the end date, and logically the function must return the value 0 in this case.

Preparation

In this assignment you will have to make use of the data types date and timedelta that are defined in the datetime module of the Python Standard Library1. Before starting to work on the actual assignment, you should first have a look at how Python responds when you execute the following sequence of instructions in an interactive Python session:

  1. >>> from datetime import date
    >>> birthday = date(1983, 1, 14)
    >>> d = date.today() - birthday
    >>> type(d)
    >>> d.days
  2. >>> from datetime import timedelta
    >>> birthday + timedelta(1)
    >>> day1 = birthday + timedelta(1)
    >>> day1
    >>> day2 = day1 + timedelta(1)
    >>> day2
  3. >>> today = date.today()
    >>> today
    >>> today.weekday()
    >>> tomorrow = today + timedelta(1)
    >>> tomorrow.weekday()
    >>> tomorrow.day

Make sure that you understand why the different results are generated.

Example

>>> from datetime import date
>>> unlucky_days(date(2012, 1, 1), date(2012, 12, 31))
3
>>> unlucky_days(date(2012, 1, 1), date(2012, 12, 31), 14, 5)
3
>>> unlucky_days(date(2012, 1, 1), date(2012, 12, 31), 17, 4)
2
>>> unlucky_days(date(2012, 1, 1), date(2012, 12, 31), 13, 1)
2
>>> unlucky_days(start_date=date(2012, 1, 1), day=1, weekday=0, end_date=date(2012, 12, 31))
1