def subtract(minuend, subtrahend):
"""Subtracts two numbers.
Args:
minuend (int/float): Value passed in by the user.
subtrahend (int/float): Value passed in by the user.
Returns:
int/float: Result of the difference from the given values.
Example:
>>> subtract(10, 5)
5
>>> subtract(-10, 4)
-14
>>> subtract(2, 0.5)
1.5
.. versionadded:: 4.0.0
"""
return call_math_operator(minuend, subtrahend, operator.sub, 0)
python类sub()的实例源码
def test_safe_binop():
# Test checked arithmetic routines
ops = [
(operator.add, 1),
(operator.sub, 2),
(operator.mul, 3)
]
with exc_iter(ops, INT64_VALUES, INT64_VALUES) as it:
for xop, a, b in it:
pyop, op = xop
c = pyop(a, b)
if not (INT64_MIN <= c <= INT64_MAX):
assert_raises(OverflowError, mt.extint_safe_binop, a, b, op)
else:
d = mt.extint_safe_binop(a, b, op)
if c != d:
# assert_equal is slow
assert_equal(d, c)
def check_sub(Poly):
# This checks commutation, not numerical correctness
c1 = list(random((4,)) + .5)
c2 = list(random((3,)) + .5)
p1 = Poly(c1)
p2 = Poly(c2)
p3 = p1 - p2
assert_poly_almost_equal(p2 - p1, -p3)
assert_poly_almost_equal(p1 - c2, p3)
assert_poly_almost_equal(c2 - p1, -p3)
assert_poly_almost_equal(p1 - tuple(c2), p3)
assert_poly_almost_equal(tuple(c2) - p1, -p3)
assert_poly_almost_equal(p1 - np.array(c2), p3)
assert_poly_almost_equal(np.array(c2) - p1, -p3)
assert_raises(TypeError, op.sub, p1, Poly([0], domain=Poly.domain + 1))
assert_raises(TypeError, op.sub, p1, Poly([0], window=Poly.window + 1))
if Poly is Polynomial:
assert_raises(TypeError, op.sub, p1, Chebyshev([0]))
else:
assert_raises(TypeError, op.sub, p1, Polynomial([0]))
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 subtract(lhs, rhs):
""" Perform element-wise subtract
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._minus,
operator.sub,
NDArray._minus_scalar,
NDArray._rminus_scalar)
# pylint: enable= no-member, protected-access
def parse_code(code):
lines = regex_flink.findall(code)
links = [[] for line in lines]
for index, line in enumerate(lines):
chains = links[index]
for word in regex_chain.findall(line):
chain = []
arity = str_arities.find(word[0])
for token in regex_token.findall(word):
if token in atoms:
chain.append(atoms[token])
elif token in quicks:
popped = []
while not quicks[token].condition(popped) and (chain or chains):
popped.insert(0, chain.pop() if chain else chains.pop())
chain += quicks[token].quicklink(popped, links, index)
elif token in hypers:
x = chain.pop() if chain else chains.pop()
chain.append(hypers[token](x, links))
else:
chain.append(create_literal(regex_liter.sub(parse_literal, token)))
chains.append(create_chain(chain, arity))
return links
def test_foldr(self):
"""
Apply a function of two arguments cumulatively to the items of
a sequence, from right to left, so as to reduce the sequence to
a single value.
"""
self.assertEqual(
irc._foldr(operator.sub, 0, [1, 2, 3, 4]),
-2)
def insertTop(l, x):
l.insert(0, x)
return l
self.assertEqual(
irc._foldr(insertTop, [], [[1], [2], [3], [4]]),
[[[[[], 4], 3], 2], 1])
def _gwas_interaction(data, *entities):
# Finding all the columns for all the targets
column_names = tuple(
tuple(name for name in data.columns if name.startswith(entity.id))
for entity in entities
)
# Finding the level column names if there are factors
factor_levels = tuple(
tuple(name[len(entity.id)+1:] for name in names)
for names, entity in zip(column_names, entities)
)
# Only creating the column name
out = {}
for cols, level_names in zip(itertools.product(*column_names),
itertools.product(*factor_levels)):
# Getting the key (for factors, if present)
key = re.sub(":{2,}", "", ":".join(level_names).strip(":"))
# Saving the columns to multiply with SNPs
out[key] = cols
return out
def test_safe_binop():
# Test checked arithmetic routines
ops = [
(operator.add, 1),
(operator.sub, 2),
(operator.mul, 3)
]
with exc_iter(ops, INT64_VALUES, INT64_VALUES) as it:
for xop, a, b in it:
pyop, op = xop
c = pyop(a, b)
if not (INT64_MIN <= c <= INT64_MAX):
assert_raises(OverflowError, mt.extint_safe_binop, a, b, op)
else:
d = mt.extint_safe_binop(a, b, op)
if c != d:
# assert_equal is slow
assert_equal(d, c)
def check_sub(Poly):
# This checks commutation, not numerical correctness
c1 = list(random((4,)) + .5)
c2 = list(random((3,)) + .5)
p1 = Poly(c1)
p2 = Poly(c2)
p3 = p1 - p2
assert_poly_almost_equal(p2 - p1, -p3)
assert_poly_almost_equal(p1 - c2, p3)
assert_poly_almost_equal(c2 - p1, -p3)
assert_poly_almost_equal(p1 - tuple(c2), p3)
assert_poly_almost_equal(tuple(c2) - p1, -p3)
assert_poly_almost_equal(p1 - np.array(c2), p3)
assert_poly_almost_equal(np.array(c2) - p1, -p3)
assert_raises(TypeError, op.sub, p1, Poly([0], domain=Poly.domain + 1))
assert_raises(TypeError, op.sub, p1, Poly([0], window=Poly.window + 1))
if Poly is Polynomial:
assert_raises(TypeError, op.sub, p1, Chebyshev([0]))
else:
assert_raises(TypeError, op.sub, p1, Polynomial([0]))
def get_numeric_subclasses(cls=numpy.number, ignore=None):
"""
Return subclasses of `cls` in the numpy scalar hierarchy.
We only return subclasses that correspond to unique data types.
The hierarchy can be seen here:
http://docs.scipy.org/doc/numpy/reference/arrays.scalars.html
"""
if ignore is None:
ignore = []
rval = []
dtype = numpy.dtype(cls)
dtype_num = dtype.num
if dtype_num not in ignore:
# Safety check: we should be able to represent 0 with this data type.
numpy.array(0, dtype=dtype)
rval.append(cls)
ignore.append(dtype_num)
for sub in cls.__subclasses__():
rval += [c for c in get_numeric_subclasses(sub, ignore=ignore)]
return rval
def op_to_opstr(op):
if op is operator.le:
return "<="
elif op is operator.ge:
return ">="
elif op is operator.eq:
return "="
elif op is operator.add:
return "+"
elif op is operator.sub:
return "-"
elif op is operator.mul:
return "*"
elif op is operator.div:
return "/"
else:
raise Exception("Operator '{}' not supported yet.", op)
def add_globals(self):
"Add some Scheme standard procedures."
import math, cmath, operator as op
from functools import reduce
self.update(vars(math))
self.update(vars(cmath))
self.update({
'+':op.add, '-':op.sub, '*':op.mul, '/':op.itruediv, 'níl':op.not_, 'agus':op.and_,
'>':op.gt, '<':op.lt, '>=':op.ge, '<=':op.le, '=':op.eq, 'mod':op.mod,
'frmh':cmath.sqrt, 'dearbhluach':abs, 'uas':max, 'íos':min,
'cothrom_le?':op.eq, 'ionann?':op.is_, 'fad':len, 'cons':cons,
'ceann':lambda x:x[0], 'tóin':lambda x:x[1:], 'iarcheangail':op.add,
'liosta':lambda *x:list(x), 'liosta?': lambda x:isa(x,list),
'folamh?':lambda x: x == [], 'adamh?':lambda x: not((isa(x, list)) or (x == None)),
'boole?':lambda x: isa(x, bool), 'scag':lambda f, x: list(filter(f, x)),
'cuir_le':lambda proc,l: proc(*l), 'mapáil':lambda p, x: list(map(p, x)),
'lódáil':lambda fn: load(fn), 'léigh':lambda f: f.read(),
'oscail_comhad_ionchuir':open,'dún_comhad_ionchuir':lambda p: p.file.close(),
'oscail_comhad_aschur':lambda f:open(f,'w'), 'dún_comhad_aschur':lambda p: p.close(),
'dac?':lambda x:x is eof_object, 'luacháil':lambda x: evaluate(x),
'scríobh':lambda x,port=sys.stdout:port.write(to_string(x) + '\n')})
return self
def sub(x, y, as_tuple=True):
""" Subtracts y from x. They can be iterables or scalars.
>>> Util.sub(1, 2)
(-1,)
>>> Util.sub((1,2,3), 1)
(0, 1, 2)
>>> Util.sub(1, [1,2,3])
(0, -1, -2)
>>> Util.sub([1, 2, 3], (4, 5, 5))
(-3, -3, -2)
"""
if Util.is_number(y): y = (y,)
x = Util.promote(x, len(y));
y = Util.promote(y, length=len(x))
assert len(x) == len(y), 'Assert that inputs are of the same length'
out = (i - j for i, j in zip(x, y))
return tuple(out) if as_tuple else out
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
def calc(self):
self.nonStreamBucket = map(operator.sub, self.allBucket, self.streamBucket)
allCount = sum(self.allBucket)
streamCount = sum(self.streamBucket)
nonStreamCount = sum(self.nonStreamBucket)
return (allCount, sum(map(lambda x: fEntropy(x, allCount), self.allBucket)), streamCount, sum(map(lambda x: fEntropy(x, streamCount), self.streamBucket)), nonStreamCount, sum(map(lambda x: fEntropy(x, nonStreamCount), self.nonStreamBucket)))
def __sub__(self, trc):
return self.apply_op2(trc, operator.sub)
def subc(a: int, b: int) -> int:
return operator.sub(a, b)
def __sub__(self, other):
return Vector(self._vectorOp(other, operator.sub), keep=True)
def __isub__(self, other):
self.values = self._vectorOp(other, operator.sub)
return self