Part 1: The Doomsday Algorithm

The Doomsday algorithm, devised by mathematician J. H. Conway, computes the day of the week any given date fell on. The algorithm is designed to be simple enough to memorize and use for mental calculation.

Example. With the algorithm, we can compute that July 4, 1776 (the day the United States declared independence from Great Britain) was a Thursday.

The algorithm is based on the fact that for any year, several dates always fall on the same day of the week, called the doomsday for the year. These dates include 4/4, 6/6, 8/8, 10/10, and 12/12.

Example. The doomsday for 2016 is Monday, so in 2016 the dates above all fell on Mondays. The doomsday for 2017 is Tuesday, so in 2017 the dates above will all fall on Tuesdays.

The doomsday algorithm has three major steps:

  1. Compute the anchor day for the target century.
  2. Compute the doomsday for the target year based on the anchor day.
  3. Determine the day of week for the target date by counting the number of days to the nearest doomsday.

Each step is explained in detail below.

The Anchor Day

The doomsday for the first year in a century is called the anchor day for that century. The anchor day is needed to compute the doomsday for any other year in that century. The anchor day for a century $c$ can be computed with the formula: $$ a = \bigl( 5 (c \bmod 4) + 2 \bigr) \bmod 7 $$ The result $a$ corresponds to a day of the week, starting with $0$ for Sunday and ending with $6$ for Saturday.

Note. The modulo operation $(x \bmod y)$ finds the remainder after dividing $x$ by $y$. For instance, $12 \bmod 3 = 0$ since the remainder after dividing $12$ by $3$ is $0$. Similarly, $11 \bmod 7 = 4$, since the remainder after dividing $11$ by $7$ is $4$.

Example. Suppose the target year is 1954, so the century is $c = 19$. Plugging this into the formula gives $$a = \bigl( 5 (19 \bmod 4) + 2 \bigr) \bmod 7 = \bigl( 5(3) + 2 \bigr) \bmod 7 = 3.$$ In other words, the anchor day for 1900-1999 is Wednesday, which is also the doomsday for 1900.

Exercise 1.1. Write a function that accepts a year as input and computes the anchor day for that year's century. The modulo operator % and functions in the math module may be useful. Document your function with a docstring and test your function for a few different years. Do this in a new cell below this one.

In [1]:
def anchor(year):
    c = year/100
    day = (((5*(c%4)) + 2)%7)
    return day

print(anchor(1900))
print(anchor(1954))
print(anchor(2011))
print(anchor(1832))
3
3
2
5

The Doomsday

Once the anchor day is known, let $y$ be the last two digits of the target year. Then the doomsday for the target year can be computed with the formula: $$d = \left(y + \left\lfloor\frac{y}{4}\right\rfloor + a\right) \bmod 7$$ The result $d$ corresponds to a day of the week.

Note. The floor operation $\lfloor x \rfloor$ rounds $x$ down to the nearest integer. For instance, $\lfloor 3.1 \rfloor = 3$ and $\lfloor 3.8 \rfloor = 3$.

Example. Again suppose the target year is 1954. Then the anchor day is $a = 3$, and $y = 54$, so the formula gives $$ d = \left(54 + \left\lfloor\frac{54}{4}\right\rfloor + 3\right) \bmod 7 = (54 + 13 + 3) \bmod 7 = 0. $$ Thus the doomsday for 1954 is Sunday.

Exercise 1.2. Write a function that accepts a year as input and computes the doomsday for that year. Your function may need to call the function you wrote in exercise 1.1. Make sure to document and test your function.

In [2]:
import math
def doomsday(year):
    y = year % 100 #last 2 digits
    a = anchor(year)
    
    d = (y + math.floor(y/4) +a)%7
    return int(d)
In [73]:
print doomsday(1901),doomsday(2012),doomsday(1954)
print doomsday(1978)
4 3 0
2

The Day of Week

The final step in the Doomsday algorithm is to count the number of days between the target date and a nearby doomsday, modulo 7. This gives the day of the week.

Every month has at least one doomsday:

  • (regular years) 1/10, 2/28
  • (leap years) 1/11, 2/29
  • 3/21, 4/4, 5/9, 6/6, 7/11, 8/8, 9/5, 10/10, 11/7, 12/12

Example. Suppose we want to find the day of the week for 7/21/1954. The doomsday for 1954 is Sunday, and a nearby doomsday is 7/11. There are 10 days in July between 7/11 and 7/21. Since $10 \bmod 7 = 3$, the date 7/21/1954 falls 3 days after a Sunday, on a Wednesday.

Exercise 1.3. Write a function to determine the day of the week for a given day, month, and year. Be careful of leap years! Your function should return a string such as "Thursday" rather than a number. As usual, document and test your code.

In [160]:
#checks to see if the year is a leap year
def isLeap(year):
    if (year%4 == 0):
        if (year%100 == 0):
            if (year % 400 == 0):
                return True
            else:
                return False
        else:
            return True
    else:
        return False

#finds remaning day between prev month and the day were checking
def daysInMonth(month, day, year):
    if (month == 2 and isLeap(year) == True):
        x = 29 - day
    elif (month == 2 and isLeap(year) == False):
        x = 28-day
    elif (month in [4, 6,9,11]):
        x=30-day
    else:
        x=31-day
        
    return x
def dayOfWeek(month, day, year):
    #creates array with the days 
    if (isLeap(year) == True):
        days = [11, 29, 4, 9, 6, 11, 8, 5, 10, 7, 12]
    else:
        days = [10, 28, 4, 9, 6, 11, 8, 5, 10, 7, 12]
    if (month >= 3):
        newDay = days[month - 2]
    else:
        newDay = days[month-1]
    dooms = doomsday(year)
    #print dooms
    if (month == 3):
        time = abs(daysInMonth(2,days[1],year) - day)
    else:
        time = abs(newDay - day)
    #print time
    #adder = 2
    #dooms = 2
    adder = time%7
    #print "time is ", adder
    # lol testdate = adder + dooms
    date = adder + dooms
    #date = 4
    if (date%7 == 0):
        x = "Sunday"
    elif (date%7 == 1):
        x = "Monday"
    elif (date%7 == 2):
        x = "Tuesday"
    elif (date%7 == 3):
        x = "Wednesday"
    elif (date%7 == 4):
        x = "Thursday"
    elif (date%7 == 5):
        x = "Friday"
    else:
        x = "Saturday"

        
    return x
In [166]:
dayOfWeek(7, 21, 1954)
Out[166]:
'Wednesday'

Exercise 1.4. How many times did Friday the 13th occur in the years 1900-1999? Does this number seem to be similar to other centuries?

In [81]:
def friyays(minYear, maxYear):
    count = 0
    for i in range(minYear,maxYear+1):
        for j in range(1,13):
            if (dayOfWeek(j,13,i) == "Friday"):
                count += 1
    return count

friyays(1900, 1999)
friyays(2000,2099)
friyays(1800,1899)
friyays(1700,1799)
Out[81]:
171

After running the code for 3 different centuries it seems like the number is similar to other centuries.

Yes, it seems like they all have approximately 172/173 friady the 13 for each century.

Exercise 1.5. How many times did Friday the 13th occur between the year 2000 and today?

In [82]:
count = 0
for i in range(2000,2018):
    for j in range(1,13):
        if (dayOfWeek(j,13,i) == "Friday"):
            count += 1

print count
30

Part 2: 1978 Birthdays

Exercise 2.1. The file birthdays.txt contains the number of births in the United States for each day in 1978. Inspect the file to determine the format. Note that columns are separated by the tab character, which can be entered in Python as \t. Write a function that uses iterators and list comprehensions with the string methods split() and strip() to convert each line of data to the list format

[month, day, year, count]

The elements of this list should be integers, not strings. The function read_birthdays provided below will help you load the file.

In [83]:
def read_birthdays(file_path):
    """Read the contents of the birthdays file into a string.
    
    Arguments:
        file_path (string): The path to the birthdays file.
        
    Returns:
        string: The contents of the birthdays file.
    """
    with open(file_path) as file:
        return file.read()
#read_birthdays("/Users/noa/Downloads/birthdays.txt")
In [153]:
def change(file_path):
    data = read_birthdays(file_path)
    data = data.strip()
    data = data.split('\n\n')[2]

    data = data.split("\t")

    #remove all the newliens
    for i in range(len(data)):
        if (data[i] == "\n"):
            break

    #list to strings
    data =  " ".join(str(x) for x in data)
    #string to list

    data = data.split()
    l = [[]]

    for i in range(0, len(data)):
        
        temp = []
        if (i%2 == 0):
            if (data[i][1] == "/"):
                #print i,data[544][0]
                month = data[i][0]
                if (data[i][3] == "/"):
                    day = data[i][2]
                    year = data[i][4:6]
                else:
                    day = data[i][2:4]
                    year = data[i][5:7]
            else:
                month = data[i][0:2]
                if (data[i][4] == "/"):
                    day = data[i][3]
                    year = data[i][5:7]
                else:
                    day = data[i][3:5]
                    year = data[i][6:8]
                
            temp.append(month)
            #print month
            temp.append(day)
            temp.append(year)
            temp.append(data[i+1])
            
        l.append(temp)

    list2 = [x for x in l if x != []] 
    #print list2
    list2 = [[int(x[y]) for y in range (0,4)] for x in list2]
    return list2

            
  
     
  #  print list2
    
#change("/Users/noa/Downloads/birthdays.txt")

Exercise 2.2. Which month had the most births in 1978? Which day of the week had the most births? Which day of the week had the fewest? What conclusions can you draw? You may find the Counter class in the collections module useful.

In [169]:
from collections import Counter
x = change("/Users/noa/Downloads/birthdays.txt")
#print x
#most births in 1978
def mostbirths(x):
    counter = 0
    temp = -1
    first = 1
    month = 1
    for i in range(0, len(x)):
        if first == x[i][0]:
            counter += x[i][3]
            continue
        if (temp < counter):
            temp = counter
            month = first
        first += 1
        counter = 0
    return month

def mostday(x, y):
    ar = [0,0,0,0,0,0,0]
    #print len(x)
    for i in range(0, len(x)):
        day = dayOfWeek(x[i][0],x[i][1],1978)
        #print "day is ", dayOfWeek(1,2,1978)
        if (day == "Sunday"):
            ar[0] += x[i][3]   
        elif (day == "Monday"):
            ar[1] += x[i][3]
        elif (day == "Tuesday"):
            ar[2] += x[i][3]
        elif (day == "Wednesday"):
            ar[3] += x[i][3]
        elif (day == "Thursday"):
            ar[4] += x[i][3]
        elif (day == "Friday"):
            ar[5] += x[i][3]
        else:
            ar[6] += x[i][3]
    #return ar
    j = 0
    if (y == "high"):
        temp = 0
        for i in range(0,len(ar)):
            if ar[i] > temp:
                temp = ar[i]
                j = i
    else:
        temp = 10**9
        for i in range(0,len(ar)):
            if ar[i] < temp:
                temp = ar[i]
                j = i 
    #print ar
    return j

print "Day of week with most births is ", mostday(x,"high")
print "Day of week with least births is ", mostday(x,"min")



           
Day of week with most births is  3
Day of week with least births is  0

From here we can see that the most birthdays occured in the month of August and on a Wednesday. We can infer that there were many birthdays on each Wednesday in August and the smallest amount of birthdays on Sundays in August.

Exercise 2.3. What would be an effective way to present the information in exercise 2.2? You don't need to write any code for this exercise, just discuss what you would do.

An effective way to prsent this information would be in a couple of graphs. Show average number of birthdays on each day of the week per month (bar chart). Another graph could be to show the number of birthdays per month.

In [ ]: