Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Combinatorics in python numpy

I’d like to write a single function that outputs all the possible combinations of 2 matrixes:

def combine(*args):
    return np.array(np.meshgrid(args)).T.reshape(-1, len(args)+1)

However when passed:

print(combine(np.array([1,2,3]), np.array([4,5,6])))

It outputs:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[[1 2 3]
 [4 5 6]]

How can I make it work? I would like to keep it automatic, not to simply pass (args[0], args[1])

>Solution :

A straight forward use of python itertools:

In [134]: import itertools
In [135]: a,b = [1,2,3], [4,5,6]
In [137]: list(itertools.product(a,b))
Out[137]: [(1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6)]

or as array:

In [145]: np.array(list(itertools.product(a,b)))
Out[145]: 
array([[1, 4],
       [1, 5],
       [1, 6],
       [2, 4],
       [2, 5],
       [2, 6],
       [3, 4],
       [3, 5],
       [3, 6]])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading