Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find all products produced by 2 unique elements of an array (python)

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
like image 575
Noob Coder Avatar asked Nov 30 '22 00:11

Noob Coder


1 Answers

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]
like image 98
TerryA Avatar answered Dec 10 '22 16:12

TerryA