Finding overlapping times...

Jonathan Gardner jgardner.jonathangardner.net at gmail.com
Thu Dec 13 19:54:23 EST 2007


On Dec 13, 3:45 pm, Breal <sean.be... at cox.net> wrote:
> I have a list that looks like the following
> [(100000, 100010), (100005, 100007), (100009, 100015)]
>
> I would like to be able to determine which of these overlap each
> other.  So, in this case, tuple 1 overlaps with tuples 2 and 3.  Tuple
> 2 overlaps with 1.  Tuple 3 overlaps with tuple 1.
>
> In my scenario I would have hundreds, if not thousands of these
> ranges.  Any nice pythonic way to do this?
>

Sure.

Start with a piece of paper and a pencil.

Write down under what conditions two tuples of numbers will overlap.
Be specific.

(Hint: two numbers can be equal, less than, or greater than each
other. That's 3 conditions. Then you can compare the first of the
first tuple to the first of the second tuple, or the first to the
second, or the second to the first, or the second to the second.
That's 4 conditions. 3x4=12 so you have 12 possible conditions when
comparing two tuples of two numbers. Describe what the result should
be for each one. Being graphical will help you get it right.)

Once you have that written down, translate it to python.

In python, write a loop that goes through each item in the list and
compares it to every other item. Remember which items compare
favorably by storing them in a list.

When the loop finishes, you should have a list of all the pairs that
match your conditions.

Since this sounds like a homework assignment, the rest is left as an
exercise to the reader.



More information about the Python-list mailing list