I would like to test multiple inequalities at once, i.e.
if (a < b < c < ...)
which is fine when all the values are present. However sometimes the numeric value of one or more of the variables to be compared may be missing/unknown; the correct behaviour in my context is to assume the associated inequality is satisfied. Let's say I assign the special value None
when the value is unknown: the behaviour I want from the <
operator (or an alternative) is:
>>> a = 1; b = 2; c = 3
>>> a < b < c # this works fine, obviously
True
>>> b = None
>>> a < b < c # would like this to return True
False
So I want to get True
if one variable is truly smaller than the other, or if one variable is missing (takes any particular pre-decided non-numerical value), or if both variables are missing, and I want to be able to string the comparisons together one go i.e. a < b < c < ...
I would also like to do this with <=
as well as <
.
Thanks
You want to test if your sequence – bar the undefined values – is in ascending order:
import operator
def isAscending(strictly, *seq):
cmp_op = operator.lt if strictly else operator.le
seq = [e for e in seq if e is not None]
return all(cmp_op(a, b) for a, b in zip(seq, seq[1:]))
a, b, c = 1, None, 2
print isAscending(True, a, b, c) # strictly ascending ?
Edited for spelling, and to use comparison operators as suggested.