How many Sundays fell on the first of the month during the 20th century (1 January 1901 to 31 December 2000)?
In Python
, if we create a datetime
variable y
then, y.strftime("%a")
will return the weekday of the date.
y=datetime(year,month,date)
weekday = y.strftime("%a")
sunday_count
by 1.from datetime import datetime sunday_count=0 for j in range(1901,2001): for k in range(1,13): y = datetime(j,k,1) if y.strftime("%a")=='Sun': sunday_count+=1 print(sunday_count)
A slightly better approach would be this.
Weekcode = { 0=Sunday, 1=Monday, 2=Tuesday, 3=Wednesday, 4=Thrusday, 5=Friday, 6=Saturday}
Generalized formula:
Weekcode on 1st of nth month of yth year
= [ ( Weekcode on 1st of (n-1)th month of yth year
) + ( No. of Days in (n-1)th month
) ] % 7
for
loop from 1900 to 2000 and for every year.sunday_count
by 1.Weekcode = 1 # Weekcode of 1st Jan 1900 is i.e. Monday months = [31,28,31,30,31,30,31,31,30,31,30,31] # no. of days in each month ordered as they occurence in a year. sunday_count = 0 # This is the sundays counter for cur_year in range(1900,2000+1) : # for loop from 1900 to 2000 # updating day count of Feb month according to the year if (cur_year%4==0 and cur_year%100!=0) or (cur_year%400==0): months[1] = 29 else: months[1] = 28 for y in months: Weekcode = (Weekcode + y)%7 if Weekcode==0 and cur_year>1900: sunday_count+=1 print(sunday_count)
RELATED TAGS
CONTRIBUTOR
View all Courses