Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

combn function in R equivalent in Python (Generate all combination of n elements)

Tags:

Function combn(x,m) in R generates all combination of the elements x taken m at a time. For instance,

t(combn(5,2))
      [,1] [,2]
 [1,]    1    2
 [2,]    1    3
 [3,]    1    4
 [4,]    1    5
 [5,]    2    3
 [6,]    2    4
 [7,]    2    5
 [8,]    3    4
 [9,]    3    5
[10,]    4    5

How can I have the same result in python? I know scipy.misc.comb gives just the result not the list and I also read this article which seems different and needs a given list at first not just simply two integer numbers.

like image 553
Hadij Avatar asked Mar 31 '18 09:03

Hadij


People also ask

What does Combn function in R do?

The combn() function in R is used to return the combination of the elements of a given argument x taken m at a time.

How do you make a combination in R?

To create combination of multiple vectors, we can use expand. grid function. For example, if we have six vectors say x, y, z, a, b, and c then the combination of vectors can be created by using the command expand.


1 Answers

itertools.combinations(iterable, r)

This generates an iterable of r length tuples. If you want it as a list, so you can see everything:

list(itertools.combinations(range(1,6), 2))
# [(1, 2), (1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5), (4, 5)]
like image 169
De Novo Avatar answered Sep 20 '22 12:09

De Novo