Python operator.lt() Examples

The following are 30 code examples of operator.lt(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module operator , or try the search function .
Example #1
Source File: test_bool.py    From ironpython2 with Apache License 2.0 7 votes vote down vote up
def test_operator(self):
        import operator
        self.assertIs(operator.truth(0), False)
        self.assertIs(operator.truth(1), True)
        with test_support.check_py3k_warnings():
            self.assertIs(operator.isCallable(0), False)
            self.assertIs(operator.isCallable(len), True)
        self.assertIs(operator.isNumberType(None), False)
        self.assertIs(operator.isNumberType(0), True)
        self.assertIs(operator.not_(1), False)
        self.assertIs(operator.not_(0), True)
        self.assertIs(operator.isSequenceType(0), False)
        self.assertIs(operator.isSequenceType([]), True)
        self.assertIs(operator.contains([], 1), False)
        self.assertIs(operator.contains([1], 1), True)
        self.assertIs(operator.isMappingType(1), False)
        self.assertIs(operator.isMappingType({}), True)
        self.assertIs(operator.lt(0, 0), False)
        self.assertIs(operator.lt(0, 1), True)
        self.assertIs(operator.is_(True, True), True)
        self.assertIs(operator.is_(True, False), False)
        self.assertIs(operator.is_not(True, True), False)
        self.assertIs(operator.is_not(True, False), True) 
Example #2
Source File: atomic_trigger_conditions.py    From scenario_runner with MIT License 6 votes vote down vote up
def __init__(self, actor, osc_position, time, along_route=False,
                 comparison_operator=operator.lt, name="InTimeToArrivalToOSCPosition"):
        """
        Setup parameters
        """
        super(InTimeToArrivalToOSCPosition, self).__init__(name)
        self._map = CarlaDataProvider.get_map()
        self._actor = actor
        self._osc_position = osc_position
        self._time = float(time)
        self._along_route = along_route
        self._comparison_operator = comparison_operator

        if self._along_route:
            # Get the global route planner, used to calculate the route
            dao = GlobalRoutePlannerDAO(self._map, 0.5)
            grp = GlobalRoutePlanner(dao)
            grp.setup()
            self._grp = grp
        else:
            self._grp = None 
Example #3
Source File: test_regression.py    From auto-alt-text-lambda-api with MIT License 6 votes vote down vote up
def test_richcompare_crash(self):
        # gh-4613
        import operator as op

        # dummy class where __array__ throws exception
        class Foo(object):
            __array_priority__ = 1002

            def __array__(self,*args,**kwargs):
                raise Exception()

        rhs = Foo()
        lhs = np.array(1)
        for f in [op.lt, op.le, op.gt, op.ge]:
            if sys.version_info[0] >= 3:
                assert_raises(TypeError, f, lhs, rhs)
            else:
                f(lhs, rhs)
        assert_(not op.eq(lhs, rhs))
        assert_(op.ne(lhs, rhs)) 
Example #4
Source File: test_arithmetic.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_comparison_flex_basic(self):
        left = pd.Series(np.random.randn(10))
        right = pd.Series(np.random.randn(10))

        tm.assert_series_equal(left.eq(right), left == right)
        tm.assert_series_equal(left.ne(right), left != right)
        tm.assert_series_equal(left.le(right), left < right)
        tm.assert_series_equal(left.lt(right), left <= right)
        tm.assert_series_equal(left.gt(right), left > right)
        tm.assert_series_equal(left.ge(right), left >= right)

        # axis
        for axis in [0, None, 'index']:
            tm.assert_series_equal(left.eq(right, axis=axis), left == right)
            tm.assert_series_equal(left.ne(right, axis=axis), left != right)
            tm.assert_series_equal(left.le(right, axis=axis), left < right)
            tm.assert_series_equal(left.lt(right, axis=axis), left <= right)
            tm.assert_series_equal(left.gt(right, axis=axis), left > right)
            tm.assert_series_equal(left.ge(right, axis=axis), left >= right)

        #
        msg = 'No axis named 1 for object type'
        for op in ['eq', 'ne', 'le', 'le', 'gt', 'ge']:
            with pytest.raises(ValueError, match=msg):
                getattr(left, op)(right, axis=1) 
Example #5
Source File: test_operators.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_compare_frame(self):
        # GH#24282 check that Categorical.__cmp__(DataFrame) defers to frame
        data = ["a", "b", 2, "a"]
        cat = Categorical(data)

        df = DataFrame(cat)

        for op in [operator.eq, operator.ne, operator.ge,
                   operator.gt, operator.le, operator.lt]:
            with pytest.raises(ValueError):
                # alignment raises unless we transpose
                op(cat, df)

        result = cat == df.T
        expected = DataFrame([[True, True, True, True]])
        tm.assert_frame_equal(result, expected)

        result = cat[::-1] != df.T
        expected = DataFrame([[False, True, True, False]])
        tm.assert_frame_equal(result, expected) 
Example #6
Source File: __init__.py    From lambda-chef-node-cleanup with Apache License 2.0 6 votes vote down vote up
def get_op(cls, op):
        ops = {
            symbol.test: cls.test,
            symbol.and_test: cls.and_test,
            symbol.atom: cls.atom,
            symbol.comparison: cls.comparison,
            'not in': lambda x, y: x not in y,
            'in': lambda x, y: x in y,
            '==': operator.eq,
            '!=': operator.ne,
            '<':  operator.lt,
            '>':  operator.gt,
            '<=': operator.le,
            '>=': operator.ge,
        }
        if hasattr(symbol, 'or_test'):
            ops[symbol.or_test] = cls.test
        return ops[op] 
Example #7
Source File: test_regression.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_richcompare_crash(self):
        # gh-4613
        import operator as op

        # dummy class where __array__ throws exception
        class Foo(object):
            __array_priority__ = 1002

            def __array__(self, *args, **kwargs):
                raise Exception()

        rhs = Foo()
        lhs = np.array(1)
        for f in [op.lt, op.le, op.gt, op.ge]:
            if sys.version_info[0] >= 3:
                assert_raises(TypeError, f, lhs, rhs)
            elif not sys.py3kwarning:
                # With -3 switch in python 2, DeprecationWarning is raised
                # which we are not interested in
                f(lhs, rhs)
        assert_(not op.eq(lhs, rhs))
        assert_(op.ne(lhs, rhs)) 
Example #8
Source File: util.py    From segpy with GNU Affero General Public License v3.0 6 votes vote down vote up
def is_sorted(iterable, key=None, reverse=False, distinct=False):
    if key is None:
        key = identity
    if reverse:
        if distinct:
            if isinstance(iterable, range) and iterable.step < 0:
                return True
            op = operator.gt
        else:
            op = operator.ge
    else:
        if distinct:
            if isinstance(iterable, range) and iterable.step > 0:
                return True
            if isinstance(iterable, SortedFrozenSet):
                return True
            op = operator.lt
        else:
            op = operator.le
    return all(op(a, b) for a, b in pairwise(map(key, iterable))) 
Example #9
Source File: __init__.py    From jbox with MIT License 6 votes vote down vote up
def get_op(cls, op):
        ops = {
            symbol.test: cls.test,
            symbol.and_test: cls.and_test,
            symbol.atom: cls.atom,
            symbol.comparison: cls.comparison,
            'not in': lambda x, y: x not in y,
            'in': lambda x, y: x in y,
            '==': operator.eq,
            '!=': operator.ne,
            '<':  operator.lt,
            '>':  operator.gt,
            '<=': operator.le,
            '>=': operator.ge,
        }
        if hasattr(symbol, 'or_test'):
            ops[symbol.or_test] = cls.test
        return ops[op] 
Example #10
Source File: utils.py    From mars with Apache License 2.0 6 votes vote down vote up
def _filter_range_index(pd_range_index, min_val, min_val_close, max_val, max_val_close):
    if is_pd_range_empty(pd_range_index):
        return pd_range_index

    raw_min, raw_max, step = pd_range_index.min(), pd_range_index.max(), _get_range_index_step(pd_range_index)

    # seek min range
    greater_func = operator.gt if min_val_close else operator.ge
    actual_min = raw_min
    while greater_func(min_val, actual_min):
        actual_min += abs(step)
    if step < 0:
        actual_min += step  # on the right side

    # seek max range
    less_func = operator.lt if max_val_close else operator.le
    actual_max = raw_max
    while less_func(max_val, actual_max):
        actual_max -= abs(step)
    if step > 0:
        actual_max += step  # on the right side

    if step > 0:
        return pd.RangeIndex(actual_min, actual_max, step)
    return pd.RangeIndex(actual_max, actual_min, step) 
Example #11
Source File: test_richcmp.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_dicts(self):
        # Verify that __eq__ and __ne__ work for dicts even if the keys and
        # values don't support anything other than __eq__ and __ne__ (and
        # __hash__).  Complex numbers are a fine example of that.
        import random
        imag1a = {}
        for i in range(50):
            imag1a[random.randrange(100)*1j] = random.randrange(100)*1j
        items = imag1a.items()
        random.shuffle(items)
        imag1b = {}
        for k, v in items:
            imag1b[k] = v
        imag2 = imag1b.copy()
        imag2[k] = v + 1.0
        self.assertTrue(imag1a == imag1a)
        self.assertTrue(imag1a == imag1b)
        self.assertTrue(imag2 == imag2)
        self.assertTrue(imag1a != imag2)
        for opname in ("lt", "le", "gt", "ge"):
            for op in opmap[opname]:
                self.assertRaises(TypeError, op, imag1a, imag2) 
Example #12
Source File: test_fractions.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def testBigComplexComparisons(self):
        self.assertFalse(F(10**23) == complex(10**23))
        self.assertRaises(TypeError, operator.gt, F(10**23), complex(10**23))
        self.assertRaises(TypeError, operator.le, F(10**23), complex(10**23))

        x = F(3, 8)
        z = complex(0.375, 0.0)
        w = complex(0.375, 0.2)
        self.assertTrue(x == z)
        self.assertFalse(x != z)
        self.assertFalse(x == w)
        self.assertTrue(x != w)
        for op in operator.lt, operator.le, operator.gt, operator.ge:
            self.assertRaises(TypeError, op, x, z)
            self.assertRaises(TypeError, op, z, x)
            self.assertRaises(TypeError, op, x, w)
            self.assertRaises(TypeError, op, w, x) 
Example #13
Source File: atomic_trigger_conditions.py    From scenario_runner with MIT License 6 votes vote down vote up
def __init__(self, actor, osc_position, distance, along_route=False,
                 comparison_operator=operator.lt, name="InTriggerDistanceToOSCPosition"):
        """
        Setup parameters
        """
        super(InTriggerDistanceToOSCPosition, self).__init__(name)
        self._actor = actor
        self._osc_position = osc_position
        self._distance = distance
        self._along_route = along_route
        self._comparison_operator = comparison_operator
        self._map = CarlaDataProvider.get_map()

        if self._along_route:
            # Get the global route planner, used to calculate the route
            dao = GlobalRoutePlannerDAO(self._map, 0.5)
            grp = GlobalRoutePlanner(dao)
            grp.setup()
            self._grp = grp
        else:
            self._grp = None 
Example #14
Source File: test_deprecations.py    From auto-alt-text-lambda-api with MIT License 5 votes vote down vote up
def test_array_richcompare_legacy_weirdness(self):
        # It doesn't really work to use assert_deprecated here, b/c part of
        # the point of assert_deprecated is to check that when warnings are
        # set to "error" mode then the error is propagated -- which is good!
        # But here we are testing a bunch of code that is deprecated *because*
        # it has the habit of swallowing up errors and converting them into
        # different warnings. So assert_warns will have to be sufficient.
        assert_warns(FutureWarning, lambda: np.arange(2) == "a")
        assert_warns(FutureWarning, lambda: np.arange(2) != "a")
        # No warning for scalar comparisons
        with warnings.catch_warnings():
            warnings.filterwarnings("error")
            assert_(not (np.array(0) == "a"))
            assert_(np.array(0) != "a")
            assert_(not (np.int16(0) == "a"))
            assert_(np.int16(0) != "a")

        for arg1 in [np.asarray(0), np.int16(0)]:
            struct = np.zeros(2, dtype="i4,i4")
            for arg2 in [struct, "a"]:
                for f in [operator.lt, operator.le, operator.gt, operator.ge]:
                    if sys.version_info[0] >= 3:
                        # py3
                        with warnings.catch_warnings() as l:
                            warnings.filterwarnings("always")
                            assert_raises(TypeError, f, arg1, arg2)
                            assert_(not l)
                    else:
                        # py2
                        assert_warns(DeprecationWarning, f, arg1, arg2) 
Example #15
Source File: core_test.py    From auto-alt-text-lambda-api with MIT License 5 votes vote down vote up
def setUp(self):
    super(CoreBinaryOpsTest, self).setUp()

    self.x_probs_broadcast_tensor = array_ops.reshape(
        self.x_probs_lt.tensor, [self.x_size, 1, self.probs_size])

    self.channel_probs_broadcast_tensor = array_ops.reshape(
        self.channel_probs_lt.tensor, [1, self.channel_size, self.probs_size])

    # == and != are not element-wise for tf.Tensor, so they shouldn't be
    # elementwise for LabeledTensor, either.
    self.ops = [
        ('add', operator.add, math_ops.add, core.add),
        ('sub', operator.sub, math_ops.subtract, core.sub),
        ('mul', operator.mul, math_ops.multiply, core.mul),
        ('div', operator.truediv, math_ops.div, core.div),
        ('mod', operator.mod, math_ops.mod, core.mod),
        ('pow', operator.pow, math_ops.pow, core.pow_function),
        ('equal', None, math_ops.equal, core.equal),
        ('less', operator.lt, math_ops.less, core.less),
        ('less_equal', operator.le, math_ops.less_equal, core.less_equal),
        ('not_equal', None, math_ops.not_equal, core.not_equal),
        ('greater', operator.gt, math_ops.greater, core.greater),
        ('greater_equal', operator.ge, math_ops.greater_equal,
         core.greater_equal),
    ]
    self.test_lt_1 = self.x_probs_lt
    self.test_lt_2 = self.channel_probs_lt
    self.test_lt_1_broadcast = self.x_probs_broadcast_tensor
    self.test_lt_2_broadcast = self.channel_probs_broadcast_tensor
    self.broadcast_axes = [self.a0, self.a1, self.a3] 
Example #16
Source File: core_test.py    From auto-alt-text-lambda-api with MIT License 5 votes vote down vote up
def test_identity(self):
    axis_order = ['w', 'x', 'y', 'z']
    lt = core.LabeledTensor(
        array_ops.reshape(math_ops.range(24), (1, 2, 3, 4)), axis_order)
    actual = core.impose_axis_order(lt, axis_order)
    self.assertLabeledTensorsEqual(lt, actual)

    lt = core.LabeledTensor(
        array_ops.reshape(math_ops.range(6), (1, 2, 3)), axis_order[:3])
    actual = core.impose_axis_order(lt, axis_order)
    self.assertLabeledTensorsEqual(lt, actual) 
Example #17
Source File: core_test.py    From auto-alt-text-lambda-api with MIT License 5 votes vote down vote up
def test_scope(self):
    axis_order = ['w', 'x', 'y', 'z']
    lt = core.LabeledTensor(array_ops.ones((1, 1, 1, 1)), axis_order)
    with core.axis_order_scope(axis_order):
      core.check_axis_order(lt) 
Example #18
Source File: core_test.py    From auto-alt-text-lambda-api with MIT License 5 votes vote down vote up
def test_invalid(self):
    axis_order = ['w', 'x', 'y', 'z']
    lt = core.LabeledTensor(array_ops.ones((1, 1, 1, 1)), axis_order)
    with self.assertRaises(core.AxisOrderError):
      core.check_axis_order(lt)
    with self.assertRaises(core.AxisOrderError):
      core.check_axis_order(lt, axis_order[:-1])
    with self.assertRaises(core.AxisOrderError):
      core.check_axis_order(lt, axis_order[::-1]) 
Example #19
Source File: core_test.py    From auto-alt-text-lambda-api with MIT License 5 votes vote down vote up
def test_slice_unknown_shape(self):
    lt = core.LabeledTensor(
        array_ops.placeholder(dtypes.float32, [None, 1]), ['x', 'y'])
    sliced_lt = core.slice_function(lt, {'y': 0})
    self.assertEqual(list(sliced_lt.axes.values()), [lt.axes['x']]) 
Example #20
Source File: core_test.py    From auto-alt-text-lambda-api with MIT License 5 votes vote down vote up
def test_reverse(self):
    axis_order = ['w', 'x', 'y', 'z']

    lt = core.LabeledTensor(
        array_ops.reshape(math_ops.range(24), (1, 2, 3, 4)), axis_order)
    actual = core.impose_axis_order(lt, axis_order[::-1])
    expected = core.transpose(lt, axis_order[::-1])
    self.assertLabeledTensorsEqual(expected, actual)

    lt = core.LabeledTensor(
        array_ops.reshape(math_ops.range(6), (1, 2, 3)), axis_order[:3])
    actual = core.impose_axis_order(lt, axis_order[::-1])
    expected = core.transpose(lt, ['y', 'x', 'w'])
    self.assertLabeledTensorsEqual(expected, actual) 
Example #21
Source File: core_test.py    From auto-alt-text-lambda-api with MIT License 5 votes vote down vote up
def test_repr(self):
    pattern = textwrap.dedent("""\
    <LabeledTensor '...' shape=(7, 3, 8, 1) dtype=float32
     axes=[('x', ...),
           ('channel', ...),
           ('y', Dimension(8)),
           ('z', Dimension(1))]>""")
    regexp = re.escape(pattern).replace(re.escape('...'), '.*')
    self.assertRegexpMatches(repr(self.lt), regexp) 
Example #22
Source File: core_test.py    From auto-alt-text-lambda-api with MIT License 5 votes vote down vote up
def setUp(self):
    tensor = array_ops.ones([7, 3, 8, 1])
    a0 = ('x', range(7))
    a1 = ('channel', ['red', 'green', 'blue'])
    a2 = ('y', 8)
    a3 = ('z', tensor_shape.Dimension(1))

    self.lt = core.LabeledTensor(tensor, [a0, a1, a2, a3]) 
Example #23
Source File: fractions.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def __lt__(a, b):
        """a < b"""
        return a._richcmp(b, operator.lt) 
Example #24
Source File: test_richcmp.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_goodentry(self):
        # This test exercises the final call to PyObject_RichCompare()
        # in Objects/listobject.c::list_richcompare()
        class Good:
            def __lt__(self, other):
                return True

        x = [Good()]
        y = [Good()]

        for op in opmap["lt"]:
            self.assertIs(op(x, y), True) 
Example #25
Source File: version.py    From arnold-usd with Apache License 2.0 5 votes vote down vote up
def __lt__(self, other): return self.__compare(other, operator.lt) 
Example #26
Source File: test_pywintypes.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def testGUIDRichCmp(self):
        s = "{00020400-0000-0000-C000-000000000046}"
        iid = pywintypes.IID(s)
        self.failIf(s==None)
        self.failIf(None==s)
        self.failUnless(s!=None)
        self.failUnless(None!=s)
        if sys.version_info > (3,0):
            self.assertRaises(TypeError, operator.gt, None, s)
            self.assertRaises(TypeError, operator.gt, s, None)
            self.assertRaises(TypeError, operator.lt, None, s)
            self.assertRaises(TypeError, operator.lt, s, None) 
Example #27
Source File: test_fractions.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def __lt__(self, other): return self._richcmp(other, operator.lt) 
Example #28
Source File: test_richcmp.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_mixed(self):
        # check that comparisons involving Vector objects
        # which return rich results (i.e. Vectors with itemwise
        # comparison results) work
        a = Vector(range(2))
        b = Vector(range(3))
        # all comparisons should fail for different length
        for opname in opmap:
            self.checkfail(ValueError, opname, a, b)

        a = range(5)
        b = 5 * [2]
        # try mixed arguments (but not (a, b) as that won't return a bool vector)
        args = [(a, Vector(b)), (Vector(a), b), (Vector(a), Vector(b))]
        for (a, b) in args:
            self.checkequal("lt", a, b, [True,  True,  False, False, False])
            self.checkequal("le", a, b, [True,  True,  True,  False, False])
            self.checkequal("eq", a, b, [False, False, True,  False, False])
            self.checkequal("ne", a, b, [True,  True,  False, True,  True ])
            self.checkequal("gt", a, b, [False, False, False, True,  True ])
            self.checkequal("ge", a, b, [False, False, True,  True,  True ])

            for ops in opmap.itervalues():
                for op in ops:
                    # calls __nonzero__, which should fail
                    self.assertRaises(TypeError, bool, op(a, b)) 
Example #29
Source File: test_richcmp.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_recursion(self):
        # Check that comparison for recursive objects fails gracefully
        from UserList import UserList
        a = UserList()
        b = UserList()
        a.append(b)
        b.append(a)
        self.assertRaises(RuntimeError, operator.eq, a, b)
        self.assertRaises(RuntimeError, operator.ne, a, b)
        self.assertRaises(RuntimeError, operator.lt, a, b)
        self.assertRaises(RuntimeError, operator.le, a, b)
        self.assertRaises(RuntimeError, operator.gt, a, b)
        self.assertRaises(RuntimeError, operator.ge, a, b)

        b.append(17)
        # Even recursive lists of different lengths are different,
        # but they cannot be ordered
        self.assertTrue(not (a == b))
        self.assertTrue(a != b)
        self.assertRaises(RuntimeError, operator.lt, a, b)
        self.assertRaises(RuntimeError, operator.le, a, b)
        self.assertRaises(RuntimeError, operator.gt, a, b)
        self.assertRaises(RuntimeError, operator.ge, a, b)
        a.append(17)
        self.assertRaises(RuntimeError, operator.eq, a, b)
        self.assertRaises(RuntimeError, operator.ne, a, b)
        a.insert(0, 11)
        b.insert(0, 12)
        self.assertTrue(not (a == b))
        self.assertTrue(a != b)
        self.assertTrue(a < b) 
Example #30
Source File: test_operator.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_lt(self):
        self.assertRaises(TypeError, operator.lt)
        self.assertRaises(TypeError, operator.lt, 1j, 2j)
        self.assertFalse(operator.lt(1, 0))
        self.assertFalse(operator.lt(1, 0.0))
        self.assertFalse(operator.lt(1, 1))
        self.assertFalse(operator.lt(1, 1.0))
        self.assertTrue(operator.lt(1, 2))
        self.assertTrue(operator.lt(1, 2.0))