Home

Awesome

✨ For a production-ready implementation please see @chaimleib's repo: chaimleib/intervaltree

Interval Tree in Python

This is an implementation of an Interval Tree as described on Wikipedia.

Usage

Objects that can be loaded into the tree must implement:

which return floats or ints.

Objects are loaded into the tree during initialization:

    IntervalTree([Interval(1, 2), Interval(4, 7), Interval(1, 8)])

You can search the tree with:

where point, begin, and end are of type float or int.

Example

 from IntervalTree import IntervalTree

 class ScheduleItem:
     def __init__(self, course_number, start_time, end_time):
         self.course_number = course_number
         self.start_time = start_time
         self.end_time = end_time
     def get_begin(self):
         return minutes_from_midnight(self.start_time)
     def get_end(self):
         return minutes_from_midnight(self.end_time)
     def __repr__(self):
         return ''.join(["{ScheduleItem: ", str((self.course_number, self.start_time, self.end_time)), "}"])

 T = IntervalTree([ScheduleItem(28374, "9:00AM", "10:00AM"), \
                   ScheduleItem(43564, "8:00AM", "12:00PM"), \
                   ScheduleItem(53453, "1:00PM", "2:00PM")])
 T.search(minutes_from_midnight("11:00AM"), minutes_from_midnight("1:30PM"))

Which returns:

[{ScheduleItem: (43564, "8:00AM", "12:00PM")}, {ScheduleItem: (53453, "1:00PM", "2:00PM")}]

Why?

Other Stuff

Hope it's useful for someone (or that you learned something)!