1 | initial version |
If a
is a list (or a tuple, or any iterable) of numbers or symbolic expressions,
sum(a)
gets you the sum of its elements.
Here is an example with numbers.
sage: sum([1, 2, 3, 4, 5])
15
Here is an example with symbolic expressions.
sage: x, y, z = SR.var("x y z")
sage: sum([x, y, z])
x + y + z
Of course you could mix the two.
sage: sum([x, y, z, 1, 2, 3])
x + y + z + 6
2 | No.2 Revision |
If The easiest are sum and product (corresponding to +
and *
): if a
is a list list
(or a tuple, or any iterable) of numbers or symbolic expressions,
expressions, sum(a)
gets you the sum of its elements.elements, prod(a)
their product.
Here is an example with numbers.
sage: sum([1, 2, 3, 4, 5])
15
sage: prod([1, 2, 3, 4, 5])
120
Here is an example with symbolic expressions.
sage: x, y, z = SR.var("x y z")
sage: sum([x, y, z])
x + y + z
sage: prod([x, y, z])
x*y*z
Of course you could mix the two.
sage: sum([x, y, z, 1, 2, 3])
x + y + z + 6
sage: prod([x, y, z, 5, 6])
30*x*y*z
Next are all
and any
(for the and
and or
operators).
sage: all(is_prime(k) for k in (3, 5, .. 11))
False
sage: any(is_prime(k) for k in (3, 5, .. 11))
True
For a more general operator, use reduce
.
sage: a = [720, 3, 4, 5]
sage: reduce(lambda x, y: x // y, a)
12
Optionally, include a start value outside the list.
sage: a = [3, 4, 5]
sage: reduce(lambda x, y: x // y, a, 720)
12