def __init__(self, code, objects=None):
self._OPERATORS = [
('|', operator.or_),
('^', operator.xor),
('&', operator.and_),
('>>', operator.rshift),
('<<', operator.lshift),
('-', operator.sub),
('+', operator.add),
('%', operator.mod),
('/', operator.truediv),
('*', operator.mul),
]
self._ASSIGN_OPERATORS = [(op + '=', opfunc)
for op, opfunc in self._OPERATORS]
self._ASSIGN_OPERATORS.append(('=', lambda cur, right: right))
self._VARNAME_PATTERN = r'[a-zA-Z_$][a-zA-Z_$0-9]*'
if objects is None:
objects = {}
self.code = code
self._functions = {}
self._objects = objects
python类mul()的实例源码
def selectname(self, name, num=10):
if not name:
return []
evalnum = int(num ** (1/len(name))) + 1
namechars = [sorted(filter(ig1, ((n, self.firstchar.get(n, 1e-10 if 0x4E00 <= ord(n) < 0x9FCD else 0)) for n in self.lookupchar(name[0]))), key=ig1, reverse=1)]
namechars.extend(sorted(filter(ig1, ((n, self.secondchar.get(n, 1e-10 if 0x4E00 <= ord(n) < 0x9FCD else 0)) for n in self.lookupchar(l))), key=ig1, reverse=1)[:evalnum] for l in name[1:])
namechars = list(filter(None, namechars))[:10]
if not namechars:
return []
candidates = []
for group in itertools.product(*namechars):
gz = tuple(zip(*group))
gname = ''.join(gz[0])
gfreq = functools.reduce(operator.mul, gz[1])
candidates.append((gname, gfreq))
candidates.sort(key=ig1, reverse=1)
return [x[0] for x in candidates][:num]
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 dotproduct(x, y):
"""dotproduct(x, y) -> int
Computes the dot product of `x` and `y`.
Arguments:
x(iterable): An iterable.
x(iterable): An iterable.
Returns:
The dot product of `x` and `y`, i.e.: ``x[0] * y[0] + x[1] * y[1] + ...``.
Example:
>>> dotproduct([1, 2, 3], [4, 5, 6])
... # 1 * 4 + 2 * 5 + 3 * 6 == 32
32
"""
return sum(imap(operator.mul, x, y))
def binaryOpTester(f, g, binop, nf, ng):
ff = Chebtech2.initfun_fixedlen(f, nf)
gg = Chebtech2.initfun_fixedlen(g, ng)
FG = lambda x: binop(f(x),g(x))
fg = binop(ff, gg)
def tester(self):
vscl = max([ff.vscale, gg.vscale])
lscl = max([ff.size, gg.size])
self.assertLessEqual(infnorm(fg(self.xx)-FG(self.xx)), 3*vscl*lscl*eps)
if binop is operator.mul:
# check simplify is not being called in __mul__
self.assertEqual(fg.size, ff.size+gg.size-1)
return tester
# note: defining __radd__(a,b) = operator.add(b,a) and feeding this into the
# test will not in fact test the __radd__ functionality of the class. These
# test need to be added manually to the class.
def _generate_normal(self, func, size, dtype, *args):
# curand functions below don't support odd size.
# * curand.generateNormal
# * curand.generateNormalDouble
# * curand.generateLogNormal
# * curand.generateLogNormalDouble
size = core.get_size(size)
element_size = six.moves.reduce(operator.mul, size, 1)
if element_size % 2 == 0:
out = cupy.empty(size, dtype=dtype)
func(self._generator, out.data.ptr, out.size, *args)
return out
else:
out = cupy.empty((element_size + 1,), dtype=dtype)
func(self._generator, out.data.ptr, out.size, *args)
return out[:element_size].reshape(size)
# NumPy compatible functions
def __mul__(self, trc):
return self.apply_op2(trc, operator.mul)
def test_vwap(context, data):
"""
Tests the vwap transform by manually keeping track of the prices
and volumes in a naiive way and asserting that our hand-rolled vwap is
the same
"""
mins = sum(context.mins_for_days[-context.days:])
for sid in data:
prices = context.price_bars[sid][-mins:]
vols = context.vol_bars[sid][-mins:]
manual_vwap = sum(
map(operator.mul, np.nan_to_num(np.array(prices)), vols),
) / sum(vols)
assert_allclose(
data[sid].vwap(context.days),
manual_vwap,
)
def rectVolume(self):
return reduce(operator.mul, self)
def __mul__(self, other):
return Vector(self._scalarOp(other, operator.mul), keep=True)
def __imul__(self, other):
self.values = self._scalarOp(other, operator.mul)
return self
def product(numbers):
"""Return the product of the numbers.
>>> product([1,2,3,4])
24
"""
return reduce(operator.mul, numbers, 1)
def test_mul (self):
c1 = pygame.Color (0x01010101)
self.assertEquals (c1.r, 1)
self.assertEquals (c1.g, 1)
self.assertEquals (c1.b, 1)
self.assertEquals (c1.a, 1)
c2 = pygame.Color (2, 5, 3, 22)
self.assertEquals (c2.r, 2)
self.assertEquals (c2.g, 5)
self.assertEquals (c2.b, 3)
self.assertEquals (c2.a, 22)
c3 = c1 * c2
self.assertEquals (c3.r, 2)
self.assertEquals (c3.g, 5)
self.assertEquals (c3.b, 3)
self.assertEquals (c3.a, 22)
c3 = c3 * c2
self.assertEquals (c3.r, 4)
self.assertEquals (c3.g, 25)
self.assertEquals (c3.b, 9)
self.assertEquals (c3.a, 255)
# Issue #286: Is type checking done for Python 3.x?
self.assertRaises (TypeError, operator.mul, c1, None)
self.assertRaises (TypeError, operator.mul, None, c1)
def vector_inner_product(self, a, b):
"""Takes the inner product of vectors a and b
a and b are lists.
This is a private function called by matrix_multiply.
"""
assert(isinstance(a, types.ListType))
assert(isinstance(b, types.ListType))
return reduce(operator.add, map(operator.mul, a, b))
def multiplication(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.mul, args, IntegerType(1))
def __imul__(self, other):
if not isinstance(self._magnitude, ndarray):
return self._mul_div(other, operator.mul)
else:
return self._imul_div(other, operator.imul)
def __mul__(self, other):
return self._mul_div(other, operator.mul)
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 _test_quantity_mul_div(self, unit, func):
func(op.mul, unit * 10.0, '4.2*meter', '42*meter', unit)
func(op.mul, '4.2*meter', unit * 10.0, '42*meter', unit)
func(op.mul, '4.2*meter', '10*inch', '42*meter*inch', unit)
func(op.truediv, unit * 42, '4.2*meter', '10/meter', unit)
func(op.truediv, '4.2*meter', unit * 10.0, '0.42*meter', unit)
func(op.truediv, '4.2*meter', '10*inch', '0.42*meter/inch', unit)