easy +10 pts

Previous Weekday Finder

Find the most recent weekday (Mon–Fri) before a given date.

Write a function `previous_weekday(date_str)` that takes a date string in the format `'YYYY-MM-DD'` and returns the date (as a string in the same format) of the most recent weekday (Monday through Friday) strictly before the given date. If the given date is a Monday, the previous weekday is the preceding Friday. The function must not modify the input; it returns a new string. Assumptions: The input is always a valid date string in `'YYYY-MM-DD'` format. The date is not the earliest possible date; you do not need to handle dates before year 1. Use the Python standard library `datetime` module (no external libraries).

Constraints

Input will be a string of format 'YYYY-MM-DD' representing a valid date. The date is guaranteed to be after '0001-01-01'. The time complexity is O(1). The function must use the `datetime` module.

Example

>>> previous_weekday('2023-11-20')
'2023-11-17'
>>> previous_weekday('2023-11-25')
'2023-11-24'
>>> previous_weekday('2023-11-26')
'2023-11-24'
10 points ~15 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Convert the input string to a `date` object using `date.fromisoformat()`.
Use `date.weekday()` where Monday is 0 and Sunday is 6. Then subtract 1 or 3 days as needed.
If the current day is Monday (0), subtract 3 days; otherwise subtract 1 day. But check: if the current day is Sunday (6), you also need to go back to Friday (2 days). Actually, for Sunday subtract 2 days, for Monday subtract 3 days, else subtract 1 day.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.