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:
Each step is explained in detail below.
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.
year = 1954
"""
This function computes the anchor day for any year (input).
"""
def anchor(year):
year = str(year)
cent = int(year[0:2])
"""cent searches for the century"""
a = (5*(cent%4) + 2)%7
return a
anchor(year)
anchor(1994)
anchor(2003)
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.
"""
Doomsday function accepts the year and returns the doomsday for that year.
"""
def doomsday(year):
year = str(year)
y = int(year[-2:])
"""y is the last two digits of target year"""
a = anchor(year)
"""Calls earlier definied anchor function"""
d = (y + (y/4) + a)%7
return d
doomsday(1990)
doomsday(1954)
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:
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.
day = 5
month = 3
year = 2004
"""
leap_year function determines if year is a leap year. Leap years are divisible by four.
"""
def leap_year(year):
year2 = str(year)
y = year2[-2:]
if (year%4 == 0):
if (y == '00' and year%400 == 0):
det_leap = 'leap'
elif (y == '00' and year%400 !=0):
det_leap = 'regular'
else:
det_leap = 'leap'
else:
det_leap = 'regular'
return det_leap
"""
dayofweek function inputs day, month, and year variables and returns the day of the
week for given date. Uses doomsday algorithm as a foundation and incorporates leap
years.
"""
def dayofweek (day, month, year):
"""Determines if leap year"""
d = leap_year(year)
"""Below matrices are doomsday dates for corresponding month by index"""
dooms_reg = [10,28,21,4,9,6,11,8,5,10,7,12]
dooms_leap = [11,29,21,4,9,6,11,8,5,10,7,12]
day_name = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']
if (d == 'regular'):
close = dooms_reg[month-1]
elif (d == 'leap'):
close = dooms_leap[month-1]
"""Btwn calculates the number of days between doomsday and input day"""
btwn = day - close
if btwn > 0:
day_index = btwn%7 + doomsday(year)
day_index = day_index%7
else:
day_index = doomsday(year)- -btwn%7
day_index = day_index%7
return (day_name[day_index])
dayofweek(day,month,year)
dayofweek(21,7,1954)
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?
day = 13
month_range = range(1,13)
year_range = range(1900,2000)
"""
fri function reads in day, month range (which will fixed) as well as
range of years. Functions counts the number of Friday the 23th occurences
and thus the true input that will change is year_range.
"""
def fri(day, month_range, year_range):
"""Starts with empty array to append into"""
tester = []
for x in year_range:
for i in month_range:
"""Checks if leap year"""
year2 = str(year)
y = year2[-2:]
if (year%4 == 0):
if (y == '00' and year%400 == 0):
det_leap = 'leap'
elif (y == '00' and year%400 !=0):
det_leap = 'regular'
else:
det_leap = 'leap'
else:
det_leap = 'regular'
dooms_reg = [10,28,21,4,9,6,11,8,5,10,7,12]
dooms_leap = [11,29,21,4,9,6,11,8,5,10,7,12]
day_name = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']
"""Finds closest doomsday depending on leap year and month"""
if (det_leap == 'regular'):
close = dooms_reg[i-1]
else:
close = dooms_leap[i-1]
"""Distance between days. Positive means day is after doomsday. Divide by 7 for week."""
btwn = day - close
if btwn > 0:
day_index = btwn%7 + doomsday(x)
day_index = day_index%7
else:
day_index = doomsday(x) - -btwn%7
day_index = day_index%7
if (day_name[day_index] == 'Friday' and day == 13 ):
"""Appends into tester dataframe to count rows"""
tester.append(i)
numrows = len(tester) # 3 rows in your example
return numrows
fri(day, month_range, range(1900,2000))
fri(day, month_range, range(1800,1900))
fri(day, month_range, range(1700,1800))
fri(day, month_range, range(1600,1700))
We see that the occurences of Friday the 13ths are similar among varying centuries.
Exercise 1.5. How many times did Friday the 13th occur between the year 2000 and today?
import time
day = 13
month_range = range(1,13)
year_range = range(2000,(2001+int(time.strftime("%y"))))
fri(day, month_range, year_range)
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.
file_path = "/Users/audreychu/Documents/4th Year/STA141B/birthdays.txt"
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()
bday = read_birthdays(file_path)
bday = bday.split("\n")
bday = bday[6:65537]
bday = filter(None, bday)
bday = bday[0:365]
month = [line.split("/")[0] for line in bday]
day = [line.split("/")[1] for line in bday]
end = [line.split("/")[2] for line in bday]
year = [line.split("\t")[0] for line in end]
count = [line.split("\t")[1] for line in end]
df = []
for line in range(0,365):
x = [int(month[line]), int(day[line]), int(year[line]), int(count[line])]
df.append(x)
df
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.
from collections import Counter
import pandas as pd
from pandas import *
month = map(int, month)
day = map(int, day)
year = map(int, year)
count = map(int, count)
new_df = pd.DataFrame({'Month': month,
'Day': day,
'Year': year,
'Count': count})
max_month = new_df.groupby(['Month'])['Count'].sum()
max_month = zip(max_month, range(1,13))
max(max_month)
Month with highest counts is August.
li = []
for i in range(1,366):
new_day = day[i-1]
new_month = month[i-1]
new_year = year[i-1]
li.append(dayofweek(new_day, new_month, 1900+new_year))
1900 + year[0]
dayofweek(day[1], month[1], year[1])
dayofweek(1,1,1978)
final_df = pd.DataFrame({'Month': month,
'Day': day,
'Year': year,
'Count': count,
'NameDay': li})
final_df
max_day = final_df.groupby(['NameDay'])['Count'].sum()
max_day
day_name = ['Friday','Monday','Saturday','Sunday','Thursday','Tuesday','Wednesday']
max_day = zip(max_day, day_name)
max(max_day)
An effect way would be through a table as I did, or rather through a data frame. Flow or organization charts would also be visually helpful--similiar to that of the video in Lesson 4.