Ask Your Question
1

How to apply a function (like the sum) among all elements of a list?

asked 2017-10-14 21:55:18 +0100

descudero gravatar image

In magma you have the possibility of invoking

&+[x0, x1, x2]

and that will return the sum of the elements in the array. You can also replace the sum operator by another binary operator that is associative. I'm wondering if SageMath has a similar feature, I've been looking in the documentation and apparently the best option is to use the built-in function sum(), but this doesn't generalize to any other binary operation.

Thanks for the help!

edit retag flag offensive close merge delete

Comments

Hey descudero, I'm having the "inverse" problem. How do you replace the sum for a associative binary operator in MAGMA? My question in fact is "how do you create an operator with MAGMA"? Thanks!

Guillermo Mosse gravatar imageGuillermo Mosse ( 2018-06-25 17:54:58 +0100 )edit

1 Answer

Sort by » oldest newest most voted
3

answered 2017-10-15 09:10:58 +0100

slelievre gravatar image

updated 2017-10-15 09:51:16 +0100

The easiest are sum and product (corresponding to + and *): 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, 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
edit flag offensive delete link more

Comments

Thanks a lot for the help! All of this makes sense, and it's very useful.

descudero gravatar imagedescudero ( 2017-10-15 16:02:36 +0100 )edit
1

reduce is not really compatible with python3

FrédéricC gravatar imageFrédéricC ( 2017-10-15 18:09:54 +0100 )edit

In Python3, reduce is no longer a built-in. Instead, use functools.reduce or an explicit for loop.

slelievre gravatar imageslelievre ( 2017-10-15 21:09:01 +0100 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2017-10-14 21:55:18 +0100

Seen: 5,089 times

Last updated: Oct 15 '17