Search code examples
pythoncombinationspython-itertools

Python combination and permuation code


I have following code to generate the set of combination, append the combination in the list, and return list.

def make_combination():
  import itertools  
  max_range = 5 
  indexes = combinations_plus = []
  for i in range(0, max_range): 
    indexes.append(i)
    for i in xrange(2, max_range): 
      each_combination = [list(x) for x in itertools.combinations(indexes, i)]
      combinations_plus.append(each_combination)
  retrun combinations_plus

It generates so many combinations that I don't want (hard to display). But, I want the following combination:

1) [[0, 1], [0, 2], [0, 3], [0, 4], [1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]

2) [[0, 1, 2], [0, 1, 3], [0, 1, 4], [0, 2, 3], [0, 2, 4], [0, 3, 4], [1, 2, 3], [1, 2, 4], [1, 3, 4], [2, 3, 4]]

3) [[0, 1, 2, 3], [0, 1, 2, 4], [0, 1, 3, 4], [0, 2, 3, 4], [1, 2, 3, 4]]

I think problem in the following line but I don't know what it is. Any idea about what the mistake is.

combinations_plus.append(each_combination)

Solution

  • An easier way of doing what you want is the following:

    list(list(itertools.combinations(list(range(5)), i)) for i in range(2, 5))