[Tutor] Reduce?
Remco Gerlich
scarblac@pino.selwerd.nl
Mon, 15 Apr 2002 18:28:23 +0200
On 0, "Jordan, Jay" <jay.jordan@eds.com> wrote:
> Here is what I am aiming for. I have a sequence of numbers N. I have a
> sequence of primes P. I want to multiply the primes each raised to the power
> of the numbers such that
>
> p1**n1*p1**n1*p3**n3...etc
>
> I know reduce is supposed to allow one to apply calculations all the way
> through a sequence but the documentation on the reduce finction is super
> sketchy. can anyone point to a better way of doing this?
The way I would do it is:
- First make the list of p1**n1 pairs. You can make pairs of the two lists
with zip(), and then use a list comprehension to make the powers list:
pairs = zip(P,N)
powers = [p**n for p, n in pairs]
- Then, multiply all elements of that list by using reduce():
import operator
total = reduce(operator.mul, powers, 1)
operator.mul is a function that multiplies two numbers; if powers is a list
of four numbers p1 to p4, reduce turns that into
((((1*p1)*p2)*p3)*p4)
The default of 1 is there in case the sequence is empty, multiplying by 1
has no effect otherwise.
You can write it all in one statement, but I wouldn't.
--
Remco Gerlich