Reputation: 717
Let's say I'm not allowed to use libraries. How do I go about calculating the product of indexes in a list. Let's assume none of the integers are 0 or less. The problem gets harder as I'm trying to calculate the indexes vertically.
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 it 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]
Upvotes: 3
Views: 94
Reputation: 221674
We can transpose the nested list and then use reduce
(a Python built-in) in Python 2.x on each element (list) for a one-liner -
>>> [reduce(lambda a,b: a*b, i) for i in map(list, zip(*bigList))]
[1, 32, 243, 1024, 3125]
Upvotes: 1
Reputation: 3157
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)
Upvotes: 0
Reputation: 22983
You can iterate over each row getting each row's n-th 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 mul_lst
function 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
Upvotes: 2
Reputation: 12927
And why not simply:
productList = []
for i in range(len(bigList[0]):
p = 1
for row in bigList:
p *= row[i]
productList.append(p)
Alternatively, a small improvement over your solution:
productList = [1]* len(bigList[0])
for row in bigList:
for i, c in enumerate(row):
productList[i] *= c
Upvotes: 1