I'm writing a program to find how many sundays on the first of a month there are between two dates.
I want to do it without using datatime.
The thing is, I obtain 173 when the expected answer is 171.
#How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?
days_of_week = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
dict_months = {"January": 31, "February": 28, "March": 31, "April": 30, "May": 31, "June": 30, "July": 31, "August": 31, "September": 30, "October": 31, "November": 30, "December": 31}
count = 0
weekday_index = -1
for year in range(1900,2001):
for month in dict_months:
#handling february
if month == "February":
#handling gap year
if year % 4 == 0:
#if year is a century it is not a leap year unless it is also a multiple of 400
if year % 100 == 0 and year % 400 != 0:
dict_months[month] = 28
else:
dict_months["February"] = 29
else:
dict_months["February"] = 28
for day in range(1, dict_months[month] 1):
weekday_index = 1
weekday = days_of_week[weekday_index]
#handling sundays
if weekday == 'Sunday':
weekday_index = -1
if day == 1:
# print(f"{month} {day} {year}")
count = 1
print(count)
CodePudding user response:
It is a simple problem. You are counting the two in 1900, when you want to count from 1901. Change to for year in range(1901,2001)
and also weekday_index = 0
since Jan 01 1901 is Tuesday. The output is then 171.