Python 如果符合条件,则更新日期和计数

Python 如果符合条件,则更新日期和计数,python,Python,我编写了以下代码: 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(): sta

我编写了以下代码:

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),有没有关于我的代码哪里出错的建议?

您的整个代码可以表示为:

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
更短的解决方案(更多出于好奇而非必要):


天哪,您的代码需要
datetime
calendar
库!当您只需执行
startDate时,为什么需要
compare()
=endDate
?因为它不起作用,我注意到您被0抛出。例如,数组中的feb是daysInMonths[1],但代码中的daysInMonths[2]=29。我建议你一直习惯使用0索引来避免类似的事情。帮助其他程序员阅读,因为我们已经习惯了!当然可以。再一次,不要使用0-12当当。@LVT,嗯<代码>日历。工作日预计为1-12月的一个月。是的,我也查了一下,那是。。。尴尬。虽然我知道他们想使用人类可读的日期,但在一种使用零基容器的语言中看到一个基于一的范围对我来说有点奇怪。无论如何,我现在知道了@LVT就是这样。
calendar
模块设计用于提供人类可读的日历,获取人类可读的输入,并提供人类可读的输出。
datetime
模块是计算机友好的版本(不过请注意,月份也是1-12!)您还可以进行一行
sum(calendar.monthrange(year,month)[0]==calendar.SUNDAY,表示范围内的年份(19012001),表示范围内的月份(1,13))
import calendar

sum(calendar.monthrange(year,month)[0]==calendar.SUNDAY 
    for year in range(1901,2001) 
    for month in range(1,13))