Hi,
I have a list of time intervals with start and end time. For example the first interval is between 12:30-13:00. How can I quickly check if e.g. 1745 (17:45) is included between any of the time intervals?
period = [[1230, 1300], [1400, 1500],[900, 1000], [1530, 1800],[1930, 2100]]
I appreciate your help.
Assuming that the set of periods is a
fixed set of
non overlapping intervals and you have potentially many searches to do, it seems to me that the best solution is to use the bisect module
import bisect
period = [[1230, 1300], [1400, 1500],[900, 1000], [1530, 1800],[1930, 2100]]
# prepare two helper arrays
scale, intervals = zip(
*sorted((end, inter) for inter in period for end in inter))
scale = list(scale)
scale.append(2401)
class NotFound(RuntimeError):
pass
def find_interval(time):
idx = bisect.bisect_left(scale, time)
if not (idx % 2) and (scale[idx] != time):
raise NotFound(time)
return intervals[idx]
if __name__ == '__main__':
i = find_interval(1735)
print(i)
Can you be sure an interval does not cross midnight (such as [2300, 0130])? If so it's trivial.
period = [[1230, 1300], [1400, 1500],[900, 1000], [1530, 1800],[1930, 2100]]
def in_interval(test,periods_list):
if test >= periods_list[0] and test <= periods_list[1]:
return True
else:
return False
val_to_test = int(input("Enter value"))
for intervals in period:
if in_interval(val_to_test,intervals):
print(f'In interval {intervals}')
Great code. Thank you both!