I’m getting a sequence of day of the week. Python code of what I want to do:
def week_days_to_string(week_days):
"""
>>> week_days_to_string(('Sunday', 'Monday', 'Tuesday'))
'Sunday to Tuesday'
>>> week_days_to_string(('Monday', 'Wednesday'))
'Monday and Wednesday'
>>> week_days_to_string(('Sunday', 'Wednesday', 'Thursday'))
'Sunday, Wednesday, Thursday'
"""
if len(week_days) == 2:
return '%s and %s' % weekdays
elif week_days_consecutive(week_days):
return '%s to %s' % (week_days[0], week_days[-1])
return ', '.join(week_days)
I just need the week_days_consecutive function (the hard part heh).
Any ideas how I could make this happen?
Clarification:
My wording and examples caused some confusion. I do not only want to limit this function to the work week. I want to consider all days of the week (S, M, T, W, T, F). My apologies for not being clear about that last night. Edited the body of the question to make it clearer.
Edit: Throwing some wrenches into it
Wraparound sequence:
>>> week_days_to_string(('Sunday', 'Monday', 'Tuesday', 'Saturday'))
'Saturday to Tuesday'
And, per @user470379 and optional:
>>> week_days_to_string(('Monday, 'Wednesday', 'Thursday', 'Friday'))
'Monday, Wednesday to Friday'
I would approach this problem by:
Here’s how you can do that, using
calendar.day_name,rangeand some for comprehensions:A few other options, depending on what you need:
If you need Python < 2.7, instead of the dict comprehension, you can use:
If you don’t want to allow Saturday and Sunday, just trim off the last two days:
If you need to wrap around after Sunday, it’s probably easiest to just check that each item is one more than the previous item, but working in modulo 7:
Update: For the extended problem, I would still stick with they day-to-index dict, but instead I would:
Here’s code to do this:
You might also try the following instead of that last
if/elif/elseblock to get an “and” between the last two items and commas between everything else:That’s a little different from the spec, but prettier in my eyes.