What's the Function Like Sum() But for Multiplication? Product()

What's the function like sum() but for multiplication? product()?

Update:

In Python 3.8, the prod function was added to the math module. See: math.prod().

Older info: Python 3.7 and prior

The function you're looking for would be called prod() or product() but Python doesn't have that function. So, you need to write your own (which is easy).

Pronouncement on prod()

Yes, that's right. Guido rejected the idea for a built-in prod() function because he thought it was rarely needed.

Alternative with reduce()

As you suggested, it is not hard to make your own using reduce() and operator.mul():

from functools import reduce  # Required in Python 3
import operator
def prod(iterable):
return reduce(operator.mul, iterable, 1)

>>> prod(range(1, 5))
24

Note, in Python 3, the reduce() function was moved to the functools module.

Specific case: Factorials

As a side note, the primary motivating use case for prod() is to compute factorials. We already have support for that in the math module:

>>> import math

>>> math.factorial(10)
3628800

Alternative with logarithms

If your data consists of floats, you can compute a product using sum() with exponents and logarithms:

>>> from math import log, exp

>>> data = [1.2, 1.5, 2.5, 0.9, 14.2, 3.8]
>>> exp(sum(map(log, data)))
218.53799999999993

>>> 1.2 * 1.5 * 2.5 * 0.9 * 14.2 * 3.8
218.53799999999998

Note, the use of log() requires that all the inputs are positive.

Is there a built-in product() in Python?

Pronouncement

Yes, that's right. Guido rejected the idea for a built-in prod() function because he thought it was rarely needed.

Python 3.8 Update

In Python 3.8, prod() was added to the math module:

>>> from math import prod
>>> prod(range(1, 11))
3628800

Alternative with reduce()

As you suggested, it is not hard to make your own using reduce() and operator.mul():

def prod(iterable):
return reduce(operator.mul, iterable, 1)

>>> prod(range(1, 5))
24

In Python 3, the reduce() function was moved to the functools module, so you would need to add:

from functools import reduce

Specific case: Factorials

As a side note, the primary motivating use case for prod() is to compute factorials. We already have support for that in the math module:

>>> import math

>>> math.factorial(10)
3628800

Alternative with logarithms

If your data consists of floats, you can compute a product using sum() with exponents and logarithms:

>>> from math import log, exp

>>> data = [1.2, 1.5, 2.5, 0.9, 14.2, 3.8]
>>> exp(sum(map(log, data)))
218.53799999999993

>>> 1.2 * 1.5 * 2.5 * 0.9 * 14.2 * 3.8
218.53799999999998

What's the function like sum() but for multiplication? product()?

Update:

In Python 3.8, the prod function was added to the math module. See: math.prod().

Older info: Python 3.7 and prior

The function you're looking for would be called prod() or product() but Python doesn't have that function. So, you need to write your own (which is easy).

Pronouncement on prod()

Yes, that's right. Guido rejected the idea for a built-in prod() function because he thought it was rarely needed.

Alternative with reduce()

As you suggested, it is not hard to make your own using reduce() and operator.mul():

from functools import reduce  # Required in Python 3
import operator
def prod(iterable):
return reduce(operator.mul, iterable, 1)

>>> prod(range(1, 5))
24

Note, in Python 3, the reduce() function was moved to the functools module.

Specific case: Factorials

As a side note, the primary motivating use case for prod() is to compute factorials. We already have support for that in the math module:

>>> import math

>>> math.factorial(10)
3628800

Alternative with logarithms

If your data consists of floats, you can compute a product using sum() with exponents and logarithms:

>>> from math import log, exp

>>> data = [1.2, 1.5, 2.5, 0.9, 14.2, 3.8]
>>> exp(sum(map(log, data)))
218.53799999999993

>>> 1.2 * 1.5 * 2.5 * 0.9 * 14.2 * 3.8
218.53799999999998

Note, the use of log() requires that all the inputs are positive.

is there a PRODUCT function like there is a SUM function in Oracle SQL?

select exp(sum(ln(col)))
from table;

edit:

if col always > 0

The sum of the products of a two-dimensional array python

In the first part of my answer I'll explain how to fix your code directly. Your code is almost correct but contains one big mistake in logic. In the second part of my answer I'll explain how to solve your problem using numpy. numpy is the standard python package to deal with arrays of numbers. If you're manipulating big arrays of numbers, there is no excuse not to use numpy.

Fixing your code

Your code uses 4 nested for-loops, with indices i and j to iterate on the first array, and indices i1 and j1 to iterate on the second array.

Thus you're multiplying every element res1[i][j] from the first array, with every element res2[i1][j1] from the second array. This is not what you want. You only want to multiply every element res1[i][j] from the first array with the corresponding element res2[i][j] from the second array: you should use the same indices for the first and the second array. Thus there should only be two nested for-loops.

s = 0
for i in range(len(res1)):
for j in range(len(res1[i])):
s += res1[i][j] * res2[i][j]

Note that I called the variable s instead of sum. This is because sum is the name of a builtin function in python. Shadowing the name of a builtin is heavily discouraged. Here is the list of builtins: https://docs.python.org/3/library/functions.html ; do not name a variable with a name from that list.

Now, in general, in python, we dislike using range(len(...)) in a for-loop. If you read the official tutorial and its section on for loops, it suggests that for-loop can be used to iterate on elements directly, rather than on indices.

For instance, here is how to iterate on one array, to sum the elements on an array, without using range(len(...)) and without using indices:

# sum the elements in an array
s = 0
for row in res1:
for x in row:
s += x

Here row is a whole row, and x is an element. We don't refer to indices at all.

Useful tools for looping are the builtin functions zip and enumerate:

  • enumerate can be used if you need access both to the elements, and to their indices;
  • zip can be used to iterate on two arrays simultaneously.

I won't show an example with enumerate, but zip is exactly what you need since you want to iterate on two arrays:

s = 0
for row1, row2 in zip(res1, res2):
for x, y in zip(row1, row2):
s += x * y

You can also use builtin function sum to write this all without += and without the initial = 0:

s = sum(x * y for row1,row2 in zip(res1, res2) for x,y in zip(row1, row2))

Using numpy

As I mentioned in the introduction, numpy is a standard python package to deal with arrays of numbers. In general, operations on arrays using numpy is much, much faster than loops on arrays in core python. Plus, code using numpy is usually easier to read than code using core python only, because there are a lot of useful functions and convenient notations. For instance, here is a simple way to achieve what you want:

import numpy as np

# convert to numpy arrays
res1 = np.array(res1)
res2 = np.array(res2)

# multiply elements with corresponding elements, then sum
s = (res1 * res2).sum()

Relevant documentation:

  • sum: .sum() or np.sum();
  • pointwise multiplication: np.multiply() or *;
  • dot product: np.dot.

How do you Multiply numbers in a loop in Python from a list of user inputs

Since you are multiplying, you must start with 1 cause anything multiplied by 0 is 0. And idk why you need sum()

total = 1
while True:
number = float(input("Enter a number and I’ll keep multiplying until you enter the number 1: "))
if number == 1:
print(f"The total is: {total}")
break
else:
total *= number

How do I multiply all the elements inside a list by each other?

You're initializing total to 1 every iteration of the loop.

The code should be (if you actually want to do it manually):

a = [2, 3, 4]
total = 1
for i in a:
total *= i

That solves your immediate problem but, if you're using Python 3.8 or higher, this functionality is in the math library:

import math
a = [2, 3, 4]
total = math.prod(a)

How can I sum the product of two list items using for loop in python?

Just zip the lists to generate pairs, multiply them and feed to sum:

>>> a = [1,2,3]
>>> b = [4,5,6]
>>> sum(x * y for x, y in zip(a, b))
32

In above zip will return iterable of tuples containing one number from both lists:

>>> list(zip(a, b))
[(1, 4), (2, 5), (3, 6)]

Then generator expression is used to multiply the numbers together:

>>> list(x*y for x, y in list(zip(a, b)))
[4, 10, 18]

Finally sum is used to sum them together for final result:

>>> sum(x*y for x, y in list(zip(a, b)))
32


Related Topics



Leave a reply



Submit