6

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.

Hadij
  • 3,661
  • 5
  • 26
  • 48

1 Answers1

5
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)]
De Novo
  • 7,120
  • 1
  • 23
  • 39
  • I checked it before; itertools.combinations(5, 2); TypeError: 'int' object is not iterable. I need a very simple, straightforward function. – Hadij Mar 31 '18 at 09:31
  • @Hadj Yes, you need an iterable. It's a different language, so there are going to be different requirements. passing range(1,6), will give you an iterable of 1 through 5 – De Novo Mar 31 '18 at 09:34
  • 1
    @Hadij, this is the "simple and straghtforward function", you need to pass him the iterable collection. The fact that you got blocked in the TypeError is that you did no read enough about it. – Netwave Mar 31 '18 at 09:34
  • After editing the post, now it works. thank you very much. @DanHall – Hadij Mar 31 '18 at 09:35
  • 1
    @Hadj your welcome. I'm glad adding the specific usage example helped you understand. If you feel this answers your question, upvote and select it as the answer: https://stackoverflow.com/help/someone-answers – De Novo Mar 31 '18 at 09:38
  • I am going to select your answer as the best one but it needs 3 minutes waiting based on Stackoverflow regulations @DanHall – Hadij Mar 31 '18 at 09:39