I've been working through some puzzles from exercism.io. Current puzzle asks me to return a date()
from input that essentially says "The 3rd Friday of December" or "The 1st Monday of October". I'd love to hear some feedback on how to clean this code up:
def meetup_day(year, month, weekday, spec_weekday):
import calendar
from datetime import date
last_day = calendar.monthrange(year, month)[1]
wkday = {'Monday': 0, 'Tuesday': 1, 'Wednesday': 2, 'Thursday': 3, 'Friday': 4, 'Saturday': 5, 'Sunday': 6}
schedule_day = wkday[weekday]
if spec_weekday == "teenth":
check_range = range(13, 20)
elif spec_weekday == "last":
check_range = range(last_day - 6, last_day + 1)
else:
spec_weekday = int(spec_weekday[0:1])
check_range = range(7 * spec_weekday - 6, 7 * spec_weekday + 1)
for index in check_range:
if index > last_day:
break
if schedule_day == calendar.weekday(year, month, index):
schedule_day = index
return date(year, month, schedule_day)
meetup_day(2014, 3, "Friday", "2nd")
meetup_day(2013, 6, "Wednesday", "4th")
meetup_day(2013, 12, "Monday", "1st")
meetup_day(2015, 5, "Tuesday", "teenth")
meetup_day(2015, 4, "Thursday", "last")
StillI'm still fairly new to Python, and datetime
stuff throws me through a loop. ChoseI chose to use calendar
as well as date
because I thought the syntax was easier to understand. However, I'm definitely open to ideas on more efficient ways to do this.
Quick note: The "teenth" thing -:
Note that "Monteenth", "Tuesteenth", etc are all made up words. There was a meetup whose members realised that there are exactly 7 days that end in '-teenth'. Therefore, one is guaranteed that each day of the week (Monday, Tuesday, ...) will have exactly one date that is named with '-teenth' in every month.
Also: Yes, I know exercism also has a focus on code review. Unfortunately, it's mostly dead.