Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find intersections of ranges of float tuples across two lists in python?

Tags:

I have two lists of the form:

lst1 = [(1.2, 4), (5, 8), (19, 21), (24.5, 26)]
lst2 = [(1, 3), (6.55, 14.871), (22, 23)]

The output I am looking to get is:

output = [(1.2, 3), (6.55, 8)]

Basically, I want the intersections between the ranges defined by the tuples across the two lists.

You can assume-

  1. the indices to be ordered within a given list. For example, in lst2:

    1 < 6.55 < 22
    
  2. the ranges to be valid (within a tuple, the startVal<=endEndVal). In lst2:

    1 < 3  and 6.55 < 14.871 and 22 < 23
    

What is an efficient way to achieve this?

like image 462
Melsauce Avatar asked Jul 31 '19 13:07

Melsauce


1 Answers

I think the best way to do this is with a list comprehension, given that both lists are the same length.

in two lists for readability:

# get the min max ranges
a = [(max(i[0], j[0]),min(i[1],j[1])) for i,j in zip(lst1, lst2)]
# check that min is smaller than max
a = [(i,j) for (i,j) in a if i < j]

or in one list:

a = [(i,j) for (i,j) in [(max(i[0], j[0]),min(i[1],j[1])) for i,j in zip(lst1, lst2)] if i < j]
like image 174
Linda Avatar answered Sep 30 '22 20:09

Linda