Zed Evans Zed Evans - 1 year ago 48
Python Question

update the date and count if if match the condition

I wrote the following code:

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()


so I'm trying to count when it's Sunday on the first day of the month , but i get a bad result (173) , any suggestion where my code went wrong?

Answer Source

Your whole code is expressible as:

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)

Or equivalently with:

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download