我写了以下代码:
daysInMonths = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
startDate = {'day': 1, 'month': 1, 'year': 1901, 'dayOfTheWeek': 3}
endDate = {'day': 31, 'month': 12, 'year': 2000, 'dayOfTheWeek': 1}
counter = 0
def update_date():
startDate['day'] += 1
startDate['dayOfTheWeek'] += 1
if startDate['dayOfTheWeek'] > 7:
startDate['dayOfTheWeek'] = 1
if startDate['day'] > daysInMonths[startDate['month'] - 1]:
startDate['day'] = 1
startDate['month'] += 1
if startDate['month'] > 12:
startDate['month'] = 1
startDate['year'] += 1
if startDate['year'] % 4 == 0 and not startDate['year'] % 100 == 0:
daysInMonths[2] = 29
def compare():
if startDate['day'] != endDate['day']:
return True
if startDate['month'] != endDate['month']:
return True
if startDate['year'] != endDate['year']:
return True
return False
while compare():
if startDate['day'] == startDate['dayOfTheWeek'] == 1:
counter += 1
print(counter)
print(startDate)
update_date()
所以我试着算一下这个月的第一天是星期天,但是我得到了一个糟糕的结果(173),我的代码出错的任何建议?
答案 0 :(得分:4)
您的整个代码可以表达为:
import calendar
import itertools
first_of_months = itertools.product(range(1901, 2001),
range(1,13),
itertools.repeat(1)):
result = sum(1 for y,m,d in first_of_months
if calendar.weekday(y,m,d) == calendar.SUNDAY)
或等同于:
from calendar import weekday, SUNDAY
total = 0
for y in range(1901, 2001):
for m in range(1, 13):
d = 1
if weekday(y, m, d) == SUNDAY:
total += 1
答案 1 :(得分:0)
更短的解决方案(出于好奇而非必要性):
{{1}}