Product of integers in a list without libraries

Let's say I am not allowed to use libraries. How can I calculate the product of indices in a list. Suppose none of the integers are 0 or less. The problem gets complicated as I try to compute the vertical indices.

bigList = [[1, 2, 3, 4, 5],
           [1, 2, 3, 4, 5],
           [1, 2, 3, 4, 5],
           [1, 2, 3, 4, 5],
           [1, 2, 3, 4, 5]]

      

With numpy, the solution for my problem would be:

import numpy as np   
print([np.prod(l) for l in zip(*bigList)])

[1, 32, 243, 1024, 3125]

      

However, without this, my solution is much more chaotic:

rotateY = [l for l in zip(*bigList)]
productList = [1]* len(bigList)
count = 0
for l in rotateY:
    for i in l:
        productList[count] *= i
    count += 1
print(productList)

[1, 32, 243, 1024, 3125]

      

+3


source to share


4 answers


And why not just:

productList = []
for i in range(len(bigList[0]):
    p = 1
    for row in bigList:
        p *= row[i]
    productList.append(p)

      



Alternatively, a slight improvement over your solution:

productList = [1]* len(bigList[0])
for row in bigList:
    for i, c in enumerate(row):
        productList[i] *= c

      

+1


source


You can iterate over each line, getting each line of the nth element, and multiplying each element together:

>>> from functools import reduce
>>> 
>>> def mul_lst(lst):
    return reduce(lambda x, y: x * y, lst)

>>> 
>>> bigList = [[1, 2, 3, 4, 5],
       [1, 2, 3, 4, 5],
       [1, 2, 3, 4, 5],
       [1, 2, 3, 4, 5],
       [1, 2, 3, 4, 5]]
>>> 
>>> [mul_lst([row[i] for row in bigList]) for i in range(len(bigList))]
[1, 32, 243, 1024, 3125]

      



If you cannot use any libraries including functools

, you can write the logic for the function mul_lst

manually:

>>> def mul_lst(lst):
    product = lst[0]
    for el in lst[1:]:
        product *= el
    return product

>>> mul_lst([3, 3])
9
>>> mul_lst([2, 2, 2, 2, 2])
32

      

+2


source


We can wrap a nested list and then use reduce

(inline Python) in Python 2.x for each item (list) for a one-liner -

>>> [reduce(lambda a,b: a*b, i) for i in map(list, zip(*bigList))]
[1, 32, 243, 1024, 3125]

      

+1


source


Here's a quick recursive solution

def prod(x):
  """ Recursive approach with behavior of np.prod over axis 0 """
  if len(x) is 1:
      return x
  for i, a_ in enumerate(x.pop()):
      x[0][i] *= a_
  return prod(x)

      

0


source







All Articles