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

Given a matrix, how can I quickly generate all tuples consisting of its row elements in python?

Suppose there is a matrix:

enter image description here

Next, I take an arbitrary element from each row of the matrix, since the matrix has m rows in total, I end up with m elements.

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

After that, I arrange these elements together to form a tuple according to the row number from small to large, that is

enter image description here

Obviously, there are 2^m such tuples in total. For example, when m=2, we will have 4 tuples, which are:

enter image description here

So, how can I program to generate these 2^m tuples quickly(In python)? Which algorithm should I use?


Note:

Input: An m×2 matrix

Output: 2^m tuples

>Solution :

itertools.product

Example:

In [1]: import itertools                                                                                    

In [2]: arr = [[1, 2], [3, 4], [5, 6]]                                                                      

In [3]: list(itertools.product(*arr))                                                                       
Out[3]: 
[(1, 3, 5),
 (1, 3, 6),
 (1, 4, 5),
 (1, 4, 6),
 (2, 3, 5),
 (2, 3, 6),
 (2, 4, 5),
 (2, 4, 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