I have a domain of values on which I want to take intersection. for example. 0 <= n1 < 2*pi and -pi <= n2 < pi now the n1 intersection n2 would be [0,pi). The ranges of n1 and n2 can be anything. I want to know if there is an easy way to do this. I am currently using nested if-else to do this. I also want to know if their intersection is null if there is no overlap.
Asked
Active
Viewed 102 times
0
-
1can you show the code you have tried – deadshot Mar 24 '22 at 07:52
-
Please provide enough code so others can better understand or reproduce the problem. – Community Mar 24 '22 at 08:28
-
Perhaps you need [this approach](https://stackoverflow.com/a/40585196/844416) – MBo Mar 24 '22 at 09:05
2 Answers
0
this is a variant:
from dataclasses import dataclass
@dataclass(frozen=True)
class Range:
frm: float
to: float
# assert frm <= to
def intersect(ranges):
if ranges[0].to < ranges[1].frm or ranges[1].to < ranges[0].frm:
# no overlap
return None
return Range(frm=max(ranges[0].frm, ranges[1].frm),
to=min(ranges[0].to, ranges[1].to))
print(intersect((Range(frm=0, to=2), Range(frm=-1, to=1))))
# -> Range(frm=0, to=1)
i used a dataclass
in order to make it a bit more clear what is going on here. note that for the Range
i assume the invariant frm <= to
.

hiro protagonist
- 44,693
- 14
- 86
- 111
0
In module sympy
there is a class Set
and several subclasses, including Interval
.
from sympy import Interval, Intersection, pi
n1 = Interval.Ropen(0, 2*pi)
n2 = Interval.Ropen(-pi, pi)
n3 = Intersection(n1, n2)
print(n3)
# Interval.Ropen(0, pi)
Relevant documentation: sympy Sets

Stef
- 13,242
- 2
- 17
- 28
-
Hi! that was very helpful. Do you know how to access the boundary values? I tried n3[0] or n3.boundary[0] got error. – Jesus Mar 26 '22 at 18:51
-
1