How to identify which numbers in a list are within each others' range
Arnaud Delobelle
arnodel at googlemail.com
Thu Jan 31 17:16:39 EST 2008
On Jan 31, 4:12 pm, erikcw <erikwickst... at gmail.com> wrote:
> Hi,
>
> I have a list of numbers each with a +/- margin of error. I need to
> identify which ones overlab each other.
>
> For example:
> 55 +/- 3
> 20 +/- 2
> 17 +/- 4
> 60 +/- 3
>
> #base, max, min
> list = [
> (55, 58, 52),
> (20, 22, 18),
> (17, 21, 13),
> (60, 63, 57),
> ]
>
> In this example the range of list[0] overlaps the range of list[3] AND
> list[1] overlaps list[2]
>
> What is the best way to in python to identify the list items that
> overlap and the items that don't overlap with any other.
This is definitely the best way:
=======================
lst = [
(55, 58, 52),
(20, 22, 18),
(17, 21, 13),
(60, 63, 57),
]
from itertools import chain
def overlaps(lst):
bounds = chain(*(((x[1],i), (x[2], i)) for i,x in enumerate(lst)))
inside = {}
for x, i in sorted(bounds):
if inside.pop(i, None) is None:
for j, y in inside.iteritems():
if y != x: yield i, j
inside[i] = x
==============================
>>> list(overlaps(lst))
[(1, 2), (3, 0)]
--
Arnaud
More information about the Python-list
mailing list