I have list of comparisons against a variable like this
['x < 0.15', 'x > -inf', 'x < 0.20', 'x > -5.5']
How can these comparisons be consolidated to result '(-5.5, 0.15)'
.
I see there's no data structure that supports representation of range of continuous real numbers in python
You can use sympy to solve system of inequalities:
In [1]: from sympy import oo, solve
In [2]: from sympy.abc import x
In [3]: from sympy.parsing.sympy_parser import parse_expr
In [4]: system = ['x < 0.15', 'x > -inf', 'x < 0.20', 'x > -5.5']
In [5]: solve([parse_expr(x, local_dict={'inf': oo}) for x in system])
Out[5]: (-5.5 < x) & (x < 0.15)
One way in pure Python:
myList = ['x < 0.15', 'x > -inf', 'x < 0.20', 'x > -5.5']
def andRange(lst):
gt = []
lt = []
for rng in lst:
if "<" in rng:
strVal = rng.split("<")[1]
if strVal.strip() != "inf":
lt.append(float(strVal))
if ">" in rng:
strVal = rng.split(">")[1]
if strVal.strip() != "-inf":
gt.append(float(strVal))
return (min(lt), max(gt))
print(andRange(myList))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.