How can I get all days between two days?

algorithm, python

Solution

>>> def weekdays_between(s, e):
...     return [n % 7 for n in range(s, e + (1 if e > s else 8))]
... 
>>> weekdays_between(2, 4)
[2, 3, 4]
>>> weekdays_between(5, 1)
[5, 6, 0, 1]

It's a bit more complex if you have to convert from/to actual days.

>>> days = 'Mon Tue Wed Thu Fri Sat Sun'.split()
>>> days_1 = {d: n for n, d in enumerate(days)}
>>> def weekdays_between(s, e): 
...     s, e = days_1[s], days_1[e]
...     return [days[n % 7] for n in range(s, e + (1 if e > s else 8))]
... 
>>> weekdays_between('Wed', 'Fri')
['Wed', 'Thu', 'Fri']
>>> weekdays_between('Sat', 'Tue')
['Sat', 'Sun', 'Mon', 'Tue']

Problem

I need all the weekdays between two days. Example: ``` Wednesday - Friday = Wednesday, Thursday, Friday 3 - 5 = 3, 4, 5 Saturday - Tuesday = Saturday, Sunday, Monday, Tuesday 6 - 2 = 6, 7, 1, 2 ``` I'm pretty sure there is a clever algorithm out there to solve this. The only algorithms I can think of use either a loop or an `if` statement. There has to be an elegant way to solve this. I use the numbers 1-7 for the weekdays, but 0-6 is fine too. The best I could come up with: ``` def between(d1, d2): alldays = [0,1,2,3,4,5,6,0,1,2,3,4,5,6] # or range(7) * 2 offset = 8 if d1 > d2 else 1 return alldays[d1:d2 + offset] between(0, 4) # [0,1,2,3,4] between(5,2) # [5,6,0,1,2] ```

Original source