Determing whether two ranges overlap

Fredrik Lundh fredrik at pythonware.com
Thu Feb 16 12:07:59 EST 2006


Robin Haswell wrote:

> I was wondering if you could give me a hand with something. If I have two
> tuples that define a range, eg: (10, 20), (15, 30), I need to determine
> whether the ranges overlap each other. The algo needs to catch:
>
> (10, 20) (15, 25)
> (15, 25) (10, 20)
> (10, 25) (15, 20)
> and
> (15, 20) (10, 25)
>
> I can think of lots of ways to do this but it's in a tight loop so I need
> it to be as efficient as possible. Any help welcome :-)

how about:

    def overlap(a, b):
        return a[1] > b[0] and a[0] < b[1]

</F>






More information about the Python-list mailing list