Business Days
Write business_days(start, end) that counts the weekdays (Monday to Friday) from start to end, both dates included. The dates are text in the form "YYYY-MM-DD". If end is before start, return 0.
The tests include the whole range from year 1 to year 9999, so walking through the days one at a time is too slow.
Understand the problem
Learn the date tools.
What does datetime.date(2024, 3, 4).weekday() return? (March 4, 2024 is a Monday. weekday() counts Monday as 0.)
weekday() gives 0 for Monday up to 6 for Sunday. So Saturday is 5 and Sunday is 6: those are the days to skip.
How do you turn "2024-03-04" into a date object?
date("2024-03-04")datetime.date.fromisoformat("2024-03-04")int("2024-03-04")
date.fromisoformat parses the YYYY-MM-DD form. (datetime.strptime(text, "%Y-%m-%d") does the same with an explicit format.)
Subtracting two dates, date(2024, 3, 11) - date(2024, 3, 4), gives what?
- A number 7
- A
timedeltaof 7 days; its.daysis 7 - A date
Date arithmetic gives a timedelta. Use .days for the whole number of days, and add one to count both ends.
Write the brute force
Write the simplest version that is correct, even if it is slow. Then you have something to test against and something to improve.
def business_days(start, end):
# Write the simple version here. It only has to be correct, not fast.
pass
Hint 1: a question to ask yourself
How can you visit every day from the start to the end?
Hint 2: the shape of the answer
Parse both dates. Starting at start, add timedelta(days=1) repeatedly while the day is not after end, and count the days whose weekday() is below 5.
Find the bottleneck
How much work is that?
From year 1 to year 9999 there are about 3.65 million days. Why is walking day by day slow?
- Dates are slow in Python
- Each step creates a date object and calls a method, millions of times
- The loop is infinite
About 3.65 million loop iterations, each making a new date and a method call: that takes seconds. The weekday pattern repeats every 7 days, so counting them one at a time is wasted work.
In any 7 consecutive days, how many are weekdays?
- 5
- 7
- It depends
Every block of 7 consecutive days holds exactly 5 weekdays, whatever day it starts on. So count the full weeks at once (5 each) and look at the few leftover days by hand.
Make it faster
Count whole weeks by arithmetic, then the leftover days.
def business_days(start, end):
# Write the faster version here.
pass
Hint 1: a question to ask yourself
How many days are there in total, and how many full weeks and leftover days does that make?
Hint 2: the pattern
days = (end - start).days + 1; weeks, extra = divmod(days, 7). The full weeks give weeks * 5. The extra days are the first extra days starting at start: count their weekdays by looking at them (at most 6).
Hint 3: pseudocode
days = (end - start).days + 1
if days <= 0: return 0
weeks, extra = divmod(days, 7)
count = weeks * 5
for i in range(extra): # at most 6 days
if (start + i days).weekday() < 5: count += 1
return count
Reflect
Brute force: one day at a time
from datetime import date, timedelta
def business_days(start, end):
day = date.fromisoformat(start)
last = date.fromisoformat(end)
count = 0
while day <= last:
if day.weekday() < 5:
count += 1
day += timedelta(days=1)
return count
Improved: full weeks by arithmetic
from datetime import date, timedelta
def business_days(start, end):
first = date.fromisoformat(start)
last = date.fromisoformat(end)
days = (last - first).days + 1
if days <= 0:
return 0
weeks, extra = divmod(days, 7)
count = weeks * 5
for i in range(extra):
if (first + timedelta(days=i)).weekday() < 5:
count += 1
return count
What this tests: the datetime module (date, timedelta, fromisoformat, weekday), divmod, and replacing a long loop with arithmetic.
The pattern: when something repeats with a fixed period (a week), count the full periods with arithmetic and handle only the remainder by hand. The same idea appears in clock arithmetic, calendars and modular counting problems.
Both ends included: the number of days from the 4th to the 8th is (8th - 4th).days + 1, five days. Forgetting the + 1 is the commonest off-by-one in date problems.
Real calendars have holidays. A real business-day function takes a list of holiday dates, or uses numpy.busday_count or the holidays package.
Cost:
| Version | Time |
|---|---|
| One day at a time | O(number of days) |
| Full weeks and a remainder | O(1) |
What an interviewer might ask next: Add a list of holidays that must not be counted. (Subtract the holidays that fall on weekdays inside the range.)
VISIBLE = 3
CASES = [
(('2024-03-04', '2024-03-08'), 5, 'a Monday to a Friday'),
(('2024-03-04', '2024-03-10'), 5, 'a full week'),
(('2024-03-09', '2024-03-10'), 0, 'a weekend'),
(('2024-03-06', '2024-03-06'), 1, 'one weekday'),
(('2024-03-09', '2024-03-09'), 0, 'one Saturday'),
(('2024-03-01', '2024-03-11'), 7, 'a Friday to the Monday after next'),
(('2024-03-11', '2024-03-04'), 0, 'the end before the start'),
(('2024-01-01', '2024-12-31'), 262, 'a whole leap year'),
(('2023-12-30', '2024-01-02'), 2, 'across New Year: Saturday to Tuesday'),
]
def REFERENCE(start, end):
from datetime import date, timedelta
first = date.fromisoformat(start)
last = date.fromisoformat(end)
days = (last - first).days + 1
if days <= 0:
return 0
weeks, extra = divmod(days, 7)
count = weeks * 5
for i in range(extra):
if (first + timedelta(days=i)).weekday() < 5:
count += 1
return count
LIMIT = 0.5
def PERF():
return [('year 1 to year 9999', ('0001-01-01', '9999-12-31')), ('year 1000 to 9000', ('1000-01-01', '9000-12-31'))]