Exchhattu
Exchhattu

Reputation: 307

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)

Upvotes: 0

Views: 167

Answers (2)

Mark Tolonen
Mark Tolonen

Reputation: 177406

To fix your original code, there were two problems:

indexes = combinations_plus = []

The above creates two names for the exact same list. Appending to either appends to both which is not what you want.

The two for statements shouldn't be nested, or the list of indexes is incomplete:

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)

In fact, initialize indexes with range and skip the first for loop:

indexes = range(max_range) # becomes [0,1,2,3,4]
combinations_plus = []

With these fixes (and fixing the spelling of return, you have:

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

Which returns (newlines added for readability):

[[[0, 1], [0, 2], [0, 3], [0, 4], [1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]],
 [[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]],
 [[0, 1, 2, 3], [0, 1, 2, 4], [0, 1, 3, 4], [0, 2, 3, 4], [1, 2, 3, 4]]]

Upvotes: 0

simonzack
simonzack

Reputation: 20928

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))

Upvotes: 1

Related Questions