Five weekends: Difference between revisions

→‎{{header|Python}}: update to Python > 3.9; PEP 8 and other minor tweaks
(→‎{{header|Python}}: update to Python > 3.9; PEP 8 and other minor tweaks)
Line 5,539:
 
=={{header|Python}}==
<syntaxhighlight lang="python">from datetime import timedelta, (date,
timedelta)
 
DAY = timedelta(days=1)
START, STOP = date(1900, 1, 1), date(2101, 1, 1)
WEEKEND = {6, 5, 4} # Sunday is day 6
FMT = '%Y %m(%B)'
 
def fiveweekendspermonth(start=START, stop=STOP):
'Compute months with five weekends between dates'
when = start
lastmonth = weekenddays = 0
fiveweekends = []
while when < stop:
year, mon, _mday, _h, _m, _s, wday, _yday, _isdst = when.timetuple()
if mon != lastmonth:
if weekenddays >= 15:
fiveweekends.append(when - DAY)
weekenddays = 0
lastmonth = mon
if wday in WEEKEND:
weekenddays += 1
when += DAY
return fiveweekends
 
def five_weekends_per_month(start: date = START,
dates = fiveweekendspermonth()
stop: date = STOP) -> list[date]:
'"""Compute months with five weekends between dates'"""
whencurrent_date = start
last_month = weekend_days = 0
fiveweekendsfive_weekends = []
while whencurrent_date < stop:
if current_date.month != last_month:
if weekenddaysweekend_days >= 15:
fiveweekendsfive_weekends.append(whencurrent_date - DAY)
weekenddaysweekend_days = 0
last_month = current_date.month
if wdaycurrent_date.weekday() in WEEKEND:
lastmonthweekend_days += mon1
whencurrent_date += DAY
return five_weekends
 
 
dates = five_weekends_per_month()
indent = ' '
print('f"There are %s{len(dates)} months of which the first and last five are:' % len(dates)")
print(indent + ('\n' + indent).join(d.strftime(FMT) for d in dates[:5]))
print(indent + '...')
print(indent + ('\n' + indent).join(d.strftime(FMT) for d in dates[-5:]))
 
years_without_five_weekends_months = (STOP.year - START.year
print('\nThere are %i years in the range that do not have months with five weekends'
% len(set(range(START.year, STOP.year)) - len({d.year for d in dates}))</syntaxhighlight>
print(f"\nThere are {years_without_five_weekends_months} years in the "
print('\nThere are %i years in the f"range that do not have months with five weekends'")</syntaxhighlight>
 
'''Alternate Algorithm'''
 
The condition is equivalent to having a thirty-one day month in which the last day of the month is a Sunday.
<syntaxhighlight lang="python">LONGMONTHS = (1, 3, 5, 7, 8, 10, 12) # Jan Mar May Jul Aug Oct Dec
 
def fiveweekendspermonth2(start=START, stop=STOP):
 
return [date(yr, month, 31)
def five_weekends_per_month2(start: date = START,
for yr in range(START.year, STOP.year)
for month in LONGMONTHS stop: date = STOP) -> list[date]:
return fiveweekends[last_day
if date(yr, month, 31).timetuple()[6] == 6 # Sunday
]for year in range(start.year, stop.year)
for month in LONG_MONTHS
if (last_day := date(yryear, month, 31)).timetupleweekday()[6] == 6] # Sunday
 
dates2 = fiveweekendspermonth2five_weekends_per_month2()
assert dates2 == dates</syntaxhighlight>
 
6

edits