Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating Combinations in python

I am not sure how to go about this in Python, if its even possible. What I need to do is create an array (or a matrix, or vector?) from 3 separate arrays. Each array as 4 elements as such, they return this:

Class1 = [1,2,3,4] Class2 = [1,2,3,4] Class3 = [1,2,3,4]

Now what I would like to do is return all possible combinations of these three classes.

Example:

1 1 1
2 1 1
3 1 1
4 1 1
1 2 1
2 2 1
3 2 1
4 2 1...

...and so on to 64 rows (4 elements *16 possible combinations for each class = 64 rows

I am hoping there is a way to do this in python. I am sure there is but I am not sure what the most efficient way to go about would be. Perhaps a "for in" loop statement that iterates over each element for each class? Or now that I am researching this, would itertools handle this?

Thanks in advance for any help offered.

like image 824
myClone Avatar asked Jul 03 '10 00:07

myClone


People also ask

How do you generate all possible combinations of two lists in Python?

The unique combination of two lists in Python can be formed by pairing each element of the first list with the elements of the second list. Method 1 : Using permutation() of itertools package and zip() function. Approach : Import itertools package and initialize list_1 and list_2.

How do you generate all possible combinations of one list?

Enter the formula =List1. Expand out the new List1 column and then Close & Load the query to a table. The table will have all the combinations of items from both lists and we saved on making a custom column in List1 and avoided using a merge query altogether!


3 Answers

What you want is called a Cartesian product:

import itertools

iterables = [ [1,2,3,4], [88,99], ['a','b'] ]

for t in itertools.product(*iterables):
    print t
like image 197
FMc Avatar answered Oct 23 '22 14:10

FMc


The simplest way:

for i in Class1:
    for j in Class2:
        for k in Class3:
            print (i,j,k)
like image 22
Aif Avatar answered Oct 23 '22 14:10

Aif


Check the Python itertools standard module:

itertools.combinations(iterable, r)

Return r length subsequences of elements from the input iterable.

like image 2
Tarantula Avatar answered Oct 23 '22 15:10

Tarantula