Question
You are given the following information, but you may prefer to do some research for yourself.
1 Jan 1900 was a Monday.
Thirty days has September,
April, June and November.
All the rest have thirty-one,
Saving February alone,
Which has twenty-eight, rain or shine.
And on leap years, twenty-nine.
A leap year occurs on any year evenly divisible by 4,
but not on a century unless it is divisible by 400.
How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?
Commentary
The lesson of this exercise: know your modules!
Python
#!/usr/bin/env python
= [
months 31,
28,
31,
30,
31,
30,
31,
31,
30,
31,
30,
31
]
= ['sun',
week 'mon',
'tue',
'wed',
'thu',
'fri',
'sat'
]
= [year for year in range(1, 101) if year % 4 == 0]
leapyears
= 0 # 1 Jan 1901
day = 0 # January
month = 1 # 1901
year = 2 # Tuesday
weekday
= {day: week[weekday]}
days
= 0
since_last_month = 0
since_last_year
= {}
first_of_months while year <= 100:
#print "%s/%s/%s - %s" % (month+1, since_last_month+1, year+1900, week[weekday])
# if it's the first of the month, make a note
# of the weekday.
if since_last_month == 0:
"%s/%s/%s" % (month+1, since_last_month+1, year+1900)] = week[weekday]
first_of_months[
# increment the counters..
+= 1
day += 1
since_last_month += 1
since_last_year
# check what year it is
= 365
days_of_year if year in leapyears:
+= 1
days_of_year if since_last_year >= days_of_year:
+= 1
year = 0
since_last_year
# check what month it is
= months[month]
days_of_month if month == 1 and year in leapyears: # february
+= 1
days_of_month if since_last_month >= days_of_month:
+= 1
month = 0
since_last_month if month > len(months)-1:
= 0
month
# check what day of the week it is
+= 1
weekday if weekday > len(week)-1:
= 0
weekday = week[weekday]
days[day]
def date_sort(date):
= date[0]
date_str = date_str.split('/')
month,day,year return int(month)*int(day)*int(year)
print(len([weekday for weekday in list(first_of_months.values()) if weekday == 'sun']))
$ time python3 first-sunday.py
real 0m0.066s
user 0m0.059s
sys 0m0.008s
Python
#!/usr/bin/env python
from calendar import monthrange; from itertools import product
print(len([(year, month) for year, month in product(list(range(1901, 2001)), list(range(1, 13))) if monthrange(year, month)[0] == 6]))
$ time python3 calendar-module-first-sunday.py
real 0m0.030s
user 0m0.022s
sys 0m0.008s
Ruby
#!/usr/bin/env ruby
require 'date'
puts Date.new(1901,1,1).upto(Date.new(2000,12,31)).find_all { |d| d.mday == 1 && d.wday == 0 }.count
$ time ruby first-sunday.rb
real 0m0.053s
user 0m0.045s
sys 0m0.008s