Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # How many Sundays fell on the first of the month during the 20th century?
- # (1 Jan 1901 to 31 Dec 2000)
- weekday = 0 #Weekday keeps track of what day of the week it is.
- #Therefore it needs to be within {0, ..., 6}
- #0 is Sunday, 1 is Monday; 6 is Saturday
- #The inital condition from the problem is that the first day is a Monday
- sunday_is_first = 0
- for year in range(1900,2001): #loops through all our years
- if year == 1901:
- sunday_is_first = 0
- #The problem statement gives us the first weekday of 1900.
- #Since we only count 1901 and onwards, we need to reset here.
- for month in range(1,13): #Month 1 is January; 12 is December
- weekday += 1
- weekday %= 7 #Makes sure it stays within {0, ..., 6}, i.e. wraps around
- if weekday == 0: #Checks if the first day of the month is indeed a Sunday
- sunday_is_first += 1
- if month == 4 or month == 6 or month == 9 or month == 11: weekday += 30 % 7
- #4 is April, 6 is June, 9 is September, 11 is November. These months have 30 days.
- #This (30 % 7) moves us to the weekday of the last day in the month.
- #The modulo operation really just keeps track of what weekday the last day of the month is.
- elif month == 2: #February
- weekday += 28 % 7
- if year % 4 == 0:
- weekday += 1 #If leap year: Adds another day to February.
- if year == 1900:
- weekday -= 1 #Centuries not divisible by 500 are _not_ leap years, thus 1900 is not.
- else: weekday += 31 % 7 #The other months have 31 days.
- print sunday_is_first
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement