Ask Your Question
0

Product of elements in a set

asked 2019-02-01 04:06:01 -0600

LukeC93 gravatar image

updated 2019-02-01 04:06:31 -0600

I have a set of numbers, and I would like to find the product of them. Generally speaking, the set of the numbers could be quite large, and will be complex, so I don't want to have to manually multiply them all. The example I have below only has 3 integer elements though..

v=[1,2,3]
S=Set(v)
S
c=S.cardinality()
c

My original thinking was something along the lines of:

 P = prod(s[i] for i in range(1,c))
 P

But I'm not sure how to: 1) define s[i] appropriately or 2) if this will work

I assume at some point I need to define I'm working in a complex field, but again, I'm not sure where I would need to do that?

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted
0

answered 2019-02-01 04:57:44 -0600

rburing gravatar image

updated 2019-02-01 05:05:43 -0600

It is simply

sage: prod(S)
6

You cannot index S because it is not ordered; you would have to convert to a list first e.g. by s = list(S).

The elements of S are of type Integer and so prod will use the product of integers.

When you add to S a complex number element like 1+I which is of type Expression, the Integers will be coerced to Expressions, the product will work in the way you expect and the result will be an Expression.

edit flag offensive delete link more

Comments

Wow - the one thing I didn't try, and it was the simplest thing! Thank you.

LukeC93 gravatar imageLukeC93 ( 2019-02-01 05:33:43 -0600 )edit
1

You can also specify a starting value for the product as an optional argument, so if you want the answer to be in CC, you could do prod(S, CC(1)).

John Palmieri gravatar imageJohn Palmieri ( 2019-02-01 12:30:05 -0600 )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: 2019-02-01 04:06:01 -0600

Seen: 65 times

Last updated: Feb 01