Weekend counter

时间:2021-05-27 15:56:03

Weekend counter

Sofia has given you a schedule and two dates and told you she needs help planning her weekends. She has asked you to count each day of rest (Saturday and Sunday) starting from the initial date to final date. You should count the initial and final dates if they fall on a Saturday or Sunday.

The dates are given as datetime.date (Read about this module here). The result is an integer.

Input: Start and end date as datetime.date.

Output: The quantity of the rest days as an integer.

原题链接: http://www.checkio.org/mission/weekend-counter/

题目大义: 数一段日期间内的周六周日数

 from datetime import date

 def checkio(from_date, to_date):
"""
Count the days of rest
"""
rel = 0
while from_date <= to_date:
if from_date.weekday() == 5 or from_date.weekday() == 6:
rel += 1
from_date += date.resolution return rel

date.resolution(day + 1)是时间步进1, 日+1

观摩veky的代码

 def checkio(d1, d2):
w1, w2 = d1.weekday(), d2.weekday()
count = (d2 - d1).days // 7 * 2
while True:
count += w2 > 4
if w1 == w2: return count
w2 = (w2 - 1) % 7

思路不错, 首先计算两个日期间的天数, 地板除7, 再乘2; 再处理其他的天数, 第五行, 或许加个括号更好理解count += (w2 > 4)