我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用operator.pow()。
def __pow__(self, y): return NonStandardInteger(operator.pow(self.val, y))
def test_exponentiation(self, input_tuple, expected): self.ureg.default_as_delta = False in1, in2 = input_tuple if type(in1) is tuple and type(in2) is tuple: in1, in2 = self.Q_(*in1), self.Q_(*in2) elif not type(in1) is tuple and type(in2) is tuple: in2 = self.Q_(*in2) else: in1 = self.Q_(*in1) input_tuple = in1, in2 expected_copy = expected[:] for i, mode in enumerate([False, True]): self.ureg.autoconvert_offset_to_baseunit = mode if expected_copy[i] == 'error': self.assertRaises((OffsetUnitCalculusError, DimensionalityError), op.pow, in1, in2) else: if type(expected_copy[i]) is tuple: expected = self.Q_(*expected_copy[i]) self.assertEqual(op.pow(in1, in2).units, expected.units) else: expected = expected_copy[i] self.assertQuantityAlmostEqual(op.pow(in1, in2), expected)
def check_pow(Poly): d = Poly.domain + random((2,))*.25 w = Poly.window + random((2,))*.25 tgt = Poly([1], domain=d, window=w) tst = Poly([1, 2, 3], domain=d, window=w) for i in range(5): assert_poly_almost_equal(tst**i, tgt) tgt = tgt * tst # default domain and window tgt = Poly([1]) tst = Poly([1, 2, 3]) for i in range(5): assert_poly_almost_equal(tst**i, tgt) tgt = tgt * tst # check error for invalid powers assert_raises(ValueError, op.pow, tgt, 1.5) assert_raises(ValueError, op.pow, tgt, -1)
def test_map(self): self.assertEqual(list(map(operator.pow, range(3), range(1,7))), [0**1, 1**2, 2**3]) def tupleize(*args): return args self.assertEqual(list(map(tupleize, 'abc', range(5))), [('a',0),('b',1),('c',2)]) self.assertEqual(list(map(tupleize, 'abc', count())), [('a',0),('b',1),('c',2)]) self.assertEqual(take(2,map(tupleize, 'abc', count())), [('a',0),('b',1)]) self.assertEqual(list(map(operator.pow, [])), []) self.assertRaises(TypeError, map) self.assertRaises(TypeError, list, map(None, range(3), range(3))) self.assertRaises(TypeError, map, operator.neg) self.assertRaises(TypeError, next, map(10, range(5))) self.assertRaises(ValueError, next, map(errfunc, [4], [5])) self.assertRaises(TypeError, next, map(onearg, [4], [5]))
def number_of_args(fn): """Return the number of positional arguments for a function, or None if the number is variable. Looks inside any decorated functions.""" try: if hasattr(fn, '__wrapped__'): return number_of_args(fn.__wrapped__) if any(p.kind == p.VAR_POSITIONAL for p in signature(fn).parameters.values()): return None else: return sum(p.kind in (p.POSITIONAL_ONLY, p.POSITIONAL_OR_KEYWORD) for p in signature(fn).parameters.values()) except ValueError: # signatures don't work for built-in operators, so check for a few explicitly UNARY_OPS = [len, op.not_, op.truth, op.abs, op.index, op.inv, op.invert, op.neg, op.pos] BINARY_OPS = [op.lt, op.le, op.gt, op.ge, op.eq, op.ne, op.is_, op.is_not, op.add, op.and_, op.floordiv, op.lshift, op.mod, op.mul, op.or_, op.pow, op.rshift, op.sub, op.truediv, op.xor, op.concat, op.contains, op.countOf, op.delitem, op.getitem, op.indexOf] TERNARY_OPS = [op.setitem] if fn in UNARY_OPS: return 1 elif fn in BINARY_OPS: return 2 elif fn in TERNARY_OPS: return 3 else: raise NotImplementedError("Bult-in operator {} not supported".format(fn))
def test_starmap(self): self.assertEqual(list(starmap(operator.pow, zip(range(3), range(1,7)))), [0**1, 1**2, 2**3]) self.assertEqual(take(3, starmap(operator.pow, zip(count(), count(1)))), [0**1, 1**2, 2**3]) self.assertEqual(list(starmap(operator.pow, [])), []) self.assertEqual(list(starmap(operator.pow, [iter([4,5])])), [4**5]) self.assertRaises(TypeError, list, starmap(operator.pow, [None])) self.assertRaises(TypeError, starmap) self.assertRaises(TypeError, starmap, operator.pow, [(4,5)], 'extra') self.assertRaises(TypeError, next, starmap(10, [(4,5)])) self.assertRaises(ValueError, next, starmap(errfunc, [(4,5)])) self.assertRaises(TypeError, next, starmap(onearg, [(4,5)])) # check copy, deepcopy, pickle ans = [0**1, 1**2, 2**3] c = starmap(operator.pow, zip(range(3), range(1,7))) self.assertEqual(list(copy.copy(c)), ans) c = starmap(operator.pow, zip(range(3), range(1,7))) self.assertEqual(list(copy.deepcopy(c)), ans) c = starmap(operator.pow, zip(range(3), range(1,7))) self.pickletest(c)
def test_takewhile(self): data = [1, 3, 5, 20, 2, 4, 6, 8] self.assertEqual(list(takewhile(underten, data)), [1, 3, 5]) self.assertEqual(list(takewhile(underten, [])), []) self.assertRaises(TypeError, takewhile) self.assertRaises(TypeError, takewhile, operator.pow) self.assertRaises(TypeError, takewhile, operator.pow, [(4,5)], 'extra') self.assertRaises(TypeError, next, takewhile(10, [(4,5)])) self.assertRaises(ValueError, next, takewhile(errfunc, [(4,5)])) t = takewhile(bool, [1, 1, 1, 0, 0, 0]) self.assertEqual(list(t), [1, 1, 1]) self.assertRaises(StopIteration, next, t) # check copy, deepcopy, pickle self.assertEqual(list(copy.copy(takewhile(underten, data))), [1, 3, 5]) self.assertEqual(list(copy.deepcopy(takewhile(underten, data))), [1, 3, 5]) self.pickletest(takewhile(underten, data))
def test_arith_flex_panel(self): ops = ['add', 'sub', 'mul', 'div', 'truediv', 'pow', 'floordiv', 'mod'] if not compat.PY3: aliases = {} else: aliases = {'div': 'truediv'} self.panel = self.panel.to_panel() for n in [np.random.randint(-50, -1), np.random.randint(1, 50), 0]: for op in ops: alias = aliases.get(op, op) f = getattr(operator, alias) exp = f(self.panel, n) result = getattr(self.panel, op)(n) assert_panel_equal(result, exp, check_panel_type=True) # rops r_f = lambda x, y: f(y, x) exp = r_f(self.panel, n) result = getattr(self.panel, 'r' + op)(n) assert_panel_equal(result, exp)
def test_arith_getitem_commute(self): df = DataFrame({'A': [1.1, 3.3], 'B': [2.5, -3.9]}) self._test_op(df, operator.add) self._test_op(df, operator.sub) self._test_op(df, operator.mul) self._test_op(df, operator.truediv) self._test_op(df, operator.floordiv) self._test_op(df, operator.pow) self._test_op(df, lambda x, y: y + x) self._test_op(df, lambda x, y: y - x) self._test_op(df, lambda x, y: y * x) self._test_op(df, lambda x, y: y / x) self._test_op(df, lambda x, y: y ** x) self._test_op(df, lambda x, y: x + y) self._test_op(df, lambda x, y: x - y) self._test_op(df, lambda x, y: x * y) self._test_op(df, lambda x, y: x / y) self._test_op(df, lambda x, y: x ** y)
def test_binary_operators(self): # skipping for now ##### raise nose.SkipTest("skipping sparse binary operators test") def _check_inplace_op(iop, op): tmp = self.bseries.copy() expected = op(tmp, self.bseries) iop(tmp, self.bseries) assert_sp_series_equal(tmp, expected) inplace_ops = ['add', 'sub', 'mul', 'truediv', 'floordiv', 'pow'] for op in inplace_ops: _check_inplace_op(getattr(operator, "i%s" % op), getattr(operator, op))
def get_default_operators(): """ generate a mapping of default operators allowed for evaluation """ return { 'u-': Func(1, operator.neg), # unary negation 'u%': Func(1, lambda a: a / Decimal(100)), # unary percentage '&': Func(2, operator.concat), '^': Func(2, operator.pow), '+': Func(2, op_add), '-': Func(2, operator.sub), '/': Func(2, operator.truediv), '*': Func(2, operator.mul), '=': Func(2, operator.eq), '<>': Func(2, lambda a, b: not operator.eq(a, b)), '>': Func(2, operator.gt), '<': Func(2, operator.lt), '>=': Func(2, operator.ge), '<=': Func(2, operator.le), }
def test_takewhile(self): data = [1, 3, 5, 20, 2, 4, 6, 8] self.assertEqual(list(takewhile(underten, data)), [1, 3, 5]) self.assertEqual(list(takewhile(underten, [])), []) self.assertRaises(TypeError, takewhile) self.assertRaises(TypeError, takewhile, operator.pow) self.assertRaises(TypeError, takewhile, operator.pow, [(4,5)], 'extra') self.assertRaises(TypeError, next, takewhile(10, [(4,5)])) self.assertRaises(ValueError, next, takewhile(errfunc, [(4,5)])) t = takewhile(bool, [1, 1, 1, 0, 0, 0]) self.assertEqual(list(t), [1, 1, 1]) self.assertRaises(StopIteration, next, t) # check copy, deepcopy, pickle self.assertEqual(list(copy.copy(takewhile(underten, data))), [1, 3, 5]) self.assertEqual(list(copy.deepcopy(takewhile(underten, data))), [1, 3, 5]) for proto in range(pickle.HIGHEST_PROTOCOL + 1): self.pickletest(proto, takewhile(underten, data))
def test_dropwhile(self): data = [1, 3, 5, 20, 2, 4, 6, 8] self.assertEqual(list(dropwhile(underten, data)), [20, 2, 4, 6, 8]) self.assertEqual(list(dropwhile(underten, [])), []) self.assertRaises(TypeError, dropwhile) self.assertRaises(TypeError, dropwhile, operator.pow) self.assertRaises(TypeError, dropwhile, operator.pow, [(4,5)], 'extra') self.assertRaises(TypeError, next, dropwhile(10, [(4,5)])) self.assertRaises(ValueError, next, dropwhile(errfunc, [(4,5)])) # check copy, deepcopy, pickle self.assertEqual(list(copy.copy(dropwhile(underten, data))), [20, 2, 4, 6, 8]) self.assertEqual(list(copy.deepcopy(dropwhile(underten, data))), [20, 2, 4, 6, 8]) for proto in range(pickle.HIGHEST_PROTOCOL + 1): self.pickletest(proto, dropwhile(underten, data))
def eval_expr(expr): import ast import operator as op op = { ast.Add: op.add, ast.Sub: op.sub, ast.Mult: op.mul, ast.Div: op.truediv, ast.Pow: op.pow, ast.BitXor: op.xor, ast.USub: op.neg, } def eval_(node): if isinstance(node, ast.Num): return fractions.Fraction(node.n) elif isinstance(node, ast.BinOp): return op[type(node.op)](eval_(node.left), eval_(node.right)) elif isinstance(node, ast.UnaryOp): return op[type(node.op)](eval_(node.operand)) raise TypeError(node) return eval_(ast.parse(str(expr), mode='eval').body)
def power(lhs, rhs): """ Perform power operator Parameters ---------- lhs : Array or float value left hand side operand rhs : Array of float value right hand side operand Returns ------- out: Array result array """ # pylint: disable= no-member, protected-access return _ufunc_helper( lhs, rhs, NDArray._power, operator.pow, NDArray._power_scalar, NDArray._rpower_scalar) # pylint: enable= no-member, protected-access
def dichotomy(self, f, kmin=2, kmax=12, raise_no_convergence=True,): """ Compute the coefficients for a function f by dichotomy. kmin, kmax: log2 of number of interpolation points to try raise_no_convergence: whether to raise an exception if the dichotomy does not converge """ for k in range(kmin, kmax): N = pow(2, k) sampled = self.sample_function(f, N) coeffs = self.polyfit(sampled) # 3) Check for negligible coefficients # If within bound: get negligible coeffs and bread bnd = self._threshold(np.max(np.abs(coeffs))) last = abs(coeffs[-2:]) if np.all(last <= bnd): break else: if raise_no_convergence: raise self.NoConvergence(last, bnd) return coeffs
def power(lhs, rhs): """ Perform power operator Parameters ---------- lhs : Array or float value left hand side operand rhs : Array of float value right hand side operand Returns ------- out: Array result array """ # pylint: disable= no-member, protected-access return _ufunc_helper( lhs, rhs, _internal._power, operator.pow, _internal._power_scalar, _internal._rpower_scalar) # pylint: enable= no-member, protected-access
def __pow__(self, trc): return self.apply_op2(trc, operator.pow)
def power(self, *args): if not len(args) > 1: raise EvaluateException('** requires at least 2 parameters!' + ' (' + str(len(args)) + ' given).') elif False in [isinstance(x, NumberType) for x in args]: raise EvaluateException('** requires all parameters to be numbers!') return reduce(op.pow, args[1:], args[0])
def test_exponentiation_array_exp(self): arr = np.array(range(3), dtype=np.float) q = self.Q_(arr, 'meter') for op_ in [op.pow, op.ipow]: q_cp = copy.copy(q) self.assertRaises(DimensionalityError, op_, 2., q_cp) arr_cp = copy.copy(arr) arr_cp = copy.copy(arr) q_cp = copy.copy(q) self.assertRaises(DimensionalityError, op_, q_cp, arr_cp) q_cp = copy.copy(q) q2_cp = copy.copy(q) self.assertRaises(DimensionalityError, op_, q_cp, q2_cp)
def test_exponentiation_array_exp_2(self): arr = np.array(range(3), dtype=np.float) #q = self.Q_(copy.copy(arr), None) q = self.Q_(copy.copy(arr), 'meter') arr_cp = copy.copy(arr) q_cp = copy.copy(q) # this fails as expected since numpy 1.8.0 but... self.assertRaises(DimensionalityError, op.pow, arr_cp, q_cp) # ..not for op.ipow ! # q_cp is treated as if it is an array. The units are ignored. # _Quantity.__ipow__ is never called arr_cp = copy.copy(arr) q_cp = copy.copy(q) self.assertRaises(DimensionalityError, op.ipow, arr_cp, q_cp)
def test_unitcontainer_arithmetic(self): x = UnitsContainer(meter=1) y = UnitsContainer(second=1) z = UnitsContainer(meter=1, second=-2) self._test_not_inplace(op.mul, x, y, UnitsContainer(meter=1, second=1)) self._test_not_inplace(op.truediv, x, y, UnitsContainer(meter=1, second=-1)) self._test_not_inplace(op.pow, z, 2, UnitsContainer(meter=2, second=-4)) self._test_not_inplace(op.pow, z, -2, UnitsContainer(meter=-2, second=4)) self._test_inplace(op.imul, x, y, UnitsContainer(meter=1, second=1)) self._test_inplace(op.itruediv, x, y, UnitsContainer(meter=1, second=-1)) self._test_inplace(op.ipow, z, 2, UnitsContainer(meter=2, second=-4)) self._test_inplace(op.ipow, z, -2, UnitsContainer(meter=-2, second=4))
def __pow__(self, other): fieldop = FieldOp(operator.pow, self, other) return R(fieldop)
def test_pow_scalar(self): self.check_array_scalar_op(operator.pow)
def test_rpow_scalar(self): self.check_array_scalar_op(operator.pow, swap=True)
def test_pow_array(self): self.check_array_array_op(operator.pow)
def test_broadcasted_pow(self): self.check_array_broadcasted_op(operator.pow)
def test_doubly_broadcasted_pow(self): self.check_array_doubly_broadcasted_op(operator.pow)
def test_flip(): flip = _f(_1)(_3, _2) assert flip(op.pow, 2, 3) == 3 ** 2
def mk_operator(which): ops = {'+':operator.add, '-':operator.sub, '*':operator.mul, '/':operator.truediv, '^':operator.pow, '&&': operator.and_, '||': operator.or_, '!':operator.not_, 'and': operator.and_, 'or': operator.or_, 'not':operator.not_, 'in': lambda x, y: operator.contains(y, x), '=':operator.eq, '<': operator.lt, '<=':operator.le, '>=':operator.ge, '>':operator.gt } return ops[which] # Token makers
def test_pow(self): self.assertRaises(TypeError, operator.pow) self.assertRaises(TypeError, operator.pow, None, None) self.assertEqual(operator.pow(3,5), 3**5) self.assertEqual(operator.__pow__(3,5), 3**5) self.assertRaises(TypeError, operator.pow, 1) self.assertRaises(TypeError, operator.pow, 1, 2, 3)
def test_starmap(self): self.assertEqual(list(starmap(operator.pow, zip(range(3), range(1,7)))), [0**1, 1**2, 2**3]) self.assertEqual(take(3, starmap(operator.pow, zip(count(), count(1)))), [0**1, 1**2, 2**3]) self.assertEqual(list(starmap(operator.pow, [])), []) self.assertEqual(list(starmap(operator.pow, [iter([4,5])])), [4**5]) self.assertRaises(TypeError, list, starmap(operator.pow, [None])) self.assertRaises(TypeError, starmap) self.assertRaises(TypeError, starmap, operator.pow, [(4,5)], 'extra') self.assertRaises(TypeError, next, starmap(10, [(4,5)])) self.assertRaises(ValueError, next, starmap(errfunc, [(4,5)])) self.assertRaises(TypeError, next, starmap(onearg, [(4,5)]))
def test_takewhile(self): data = [1, 3, 5, 20, 2, 4, 6, 8] underten = lambda x: x<10 self.assertEqual(list(takewhile(underten, data)), [1, 3, 5]) self.assertEqual(list(takewhile(underten, [])), []) self.assertRaises(TypeError, takewhile) self.assertRaises(TypeError, takewhile, operator.pow) self.assertRaises(TypeError, takewhile, operator.pow, [(4,5)], 'extra') self.assertRaises(TypeError, next, takewhile(10, [(4,5)])) self.assertRaises(ValueError, next, takewhile(errfunc, [(4,5)])) t = takewhile(bool, [1, 1, 1, 0, 0, 0]) self.assertEqual(list(t), [1, 1, 1]) self.assertRaises(StopIteration, next, t)
def test_dropwhile(self): data = [1, 3, 5, 20, 2, 4, 6, 8] underten = lambda x: x<10 self.assertEqual(list(dropwhile(underten, data)), [20, 2, 4, 6, 8]) self.assertEqual(list(dropwhile(underten, [])), []) self.assertRaises(TypeError, dropwhile) self.assertRaises(TypeError, dropwhile, operator.pow) self.assertRaises(TypeError, dropwhile, operator.pow, [(4,5)], 'extra') self.assertRaises(TypeError, next, dropwhile(10, [(4,5)])) self.assertRaises(ValueError, next, dropwhile(errfunc, [(4,5)]))
def test_stapmap(self): self.assertEqual(list(starmap(pow, [(2,5), (3,2), (10,3)])), [32, 9, 1000])
def test_map(self): for s in (range(10), range(0), range(100), (7,11), range(20,50,5)): for g in (G, I, Ig, S, L, R): self.assertEqual(list(map(onearg, g(s))), [onearg(x) for x in g(s)]) self.assertEqual(list(map(operator.pow, g(s), g(s))), [x**x for x in g(s)]) self.assertRaises(TypeError, map, onearg, X(s)) self.assertRaises(TypeError, map, onearg, N(s)) self.assertRaises(ZeroDivisionError, list, map(onearg, E(s)))
def test_starmap(self): for s in (range(10), range(0), range(100), (7,11), range(20,50,5)): for g in (G, I, Ig, S, L, R): ss = lzip(s, s) self.assertEqual(list(starmap(operator.pow, g(ss))), [x**x for x in g(s)]) self.assertRaises(TypeError, starmap, operator.pow, X(ss)) self.assertRaises(TypeError, starmap, operator.pow, N(ss)) self.assertRaises(ZeroDivisionError, list, starmap(operator.pow, E(ss)))
def __rpow__(self, y): return NonStandardInteger(operator.pow(y, self.val))
def apply_pow(left: Column, right): if type(right) == Column: result, index = apply_fast_pow(left.values, right.values, left.index, right.index) return Column(result, index) else: return Column(operator.pow(left.values, right), left.index)
def test_pow(self): self.assertRaises(TypeError, operator.pow) self.assertRaises(TypeError, operator.pow, None, None) self.assertTrue(operator.pow(3,5) == 3**5) self.assertTrue(operator.__pow__(3,5) == 3**5) self.assertRaises(TypeError, operator.pow, 1) self.assertRaises(TypeError, operator.pow, 1, 2, 3)
def test_imap(self): self.assertEqual(list(imap(operator.pow, range(3), range(1,7))), [0**1, 1**2, 2**3]) self.assertEqual(list(imap(None, 'abc', range(5))), [('a',0),('b',1),('c',2)]) self.assertEqual(list(imap(None, 'abc', count())), [('a',0),('b',1),('c',2)]) self.assertEqual(take(2,imap(None, 'abc', count())), [('a',0),('b',1)]) self.assertEqual(list(imap(operator.pow, [])), []) self.assertRaises(TypeError, imap) self.assertRaises(TypeError, imap, operator.neg) self.assertRaises(TypeError, imap(10, range(5)).next) self.assertRaises(ValueError, imap(errfunc, [4], [5]).next) self.assertRaises(TypeError, imap(onearg, [4], [5]).next)
def test_takewhile(self): data = [1, 3, 5, 20, 2, 4, 6, 8] underten = lambda x: x<10 self.assertEqual(list(takewhile(underten, data)), [1, 3, 5]) self.assertEqual(list(takewhile(underten, [])), []) self.assertRaises(TypeError, takewhile) self.assertRaises(TypeError, takewhile, operator.pow) self.assertRaises(TypeError, takewhile, operator.pow, [(4,5)], 'extra') self.assertRaises(TypeError, takewhile(10, [(4,5)]).next) self.assertRaises(ValueError, takewhile(errfunc, [(4,5)]).next) t = takewhile(bool, [1, 1, 1, 0, 0, 0]) self.assertEqual(list(t), [1, 1, 1]) self.assertRaises(StopIteration, t.next)