How do you determine the product/sum/difference/division of all the numbers in an array in python? For example for multiplication:
array=[1,2,3,4]
output will just be 1*2, 1*3, 1*4, 2*3, 2*4, 3*4:
[2,3,4,6,8,12]
I understand how "for" and "while" loops work but have been unable to figure out the solution-- how do I find every unique set of 2 variables in an array of len(array) variables? After I do that I can just do the corresponding multiplication/division/subtraction/etc.
At best all I could make was the product of an array:
array=[1,2,3]
product = 1
for i in array:
product *= i
print product
Use itertools.combinations
:
>>> from itertools import combinations
>>> array = [1, 2, 3, 4]
>>> [i * j for i, j in combinations(array, 2)]
[2, 3, 4, 6, 8, 12]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With