Reputation: 33
Hi everybody I have a small issue of coding:
I have a list of numbers from 0
to 6
that represent days of the week from Sunday to Saturday
So Sunday = 0
and Saturday = 6
So the list is [0,1,2,3,4,5,6]
There is no problem to retrieve the list between two days (or number) if the from < to.
example:
from Monday= 1
to Thursday= 4
there are these numbers included : [1,2,3,4]
Problems come when you have to retrieve the list of days when from > to:
example:
from Friday = 5
to Tuesday =2
we need to catch this list : [5, 6, 0, 1, 2]
Do you have idea how can I code an algorithm or a function that will give me a list of days (here numbers) to include if I give a number "from" and a number "to" whatever "from" is inferior or superior to the "to" value.
Thank you very much for your help.
Upvotes: 0
Views: 93
Reputation: 503
days_of_week = [0,1,2,3,4,5,6]
day_1 = 5
day_2 = 2
def days_needed(days_of_week, day_1, day_2, rollover=True):
if rollover:
day_list = days_of_week[day_1:day_2 - 1:-1]
else:
day_list = days_of_week[day_1:day_2 + 1]
return day_list
day_list = days_needed(days_of_week,day_1,day_2,rollover=True)
print(day_list)
This should do it. Let me know if you need any tweaking.
Upvotes: 0
Reputation: 775
I would do it this way:
def getweekdays(frm, to):
days = [0,1,2,3,4,5,6]
if frm <= to:
return days[frm:to+1]
else:
return days[frm:] + days[:to+1]
(I haven't checked the code, but you get the idea :) )
Upvotes: 4
Reputation: 71451
You can use list slicing:
s = [0,1,2,3,4,5,6]
days_of_week = dict(zip(['sun', 'mon', 'tue', 'wed', 'th', 'fri', 'sat'], s))
def get_days(day_range):
return range(days_of_week[day_range[0]], days_of_week[day_range[-1]]+1) if days_of_week[day_range[0]] <= days_of_week[day_range[-1]] else s[days_of_week[day_range[0]]:]+s[:days_of_week[day_range[-1]]+1]
ranges = [['fri', 'tue'], ['th', 'sat'], ['mon', 'th']]
print(list(map(get_days, ranges))))
Output:
[[5, 6, 0, 1, 2], [4, 5, 6], [1, 2, 3, 4]]
Upvotes: 0
Reputation: 34
The easiest aproach for this would be:
day = first_day
while int day != last_day:
interval_days.add(day)
if day > 6:
day = 0
Initialize the day counter at the bottom limit of the day, then keep increasing the counter until the day matches the top limit, if it goes over the biggest day (6) you set it back into the first day of the week(0).
Upvotes: 0