0

I have two integers n and m. I need to generate all possible combinations but with this order:

For n = 3 and m = 4, 
combinations = [[0, 0, 0], [0, 0, 1], [0, 0, 2], [0, 0, 3], [0, 1, 0], [0, 1, 1], [0, 1, 2], [0, 1, 3], [0, 2, 0], [0, 2, 1], [0, 2, 2], [0, 2, 3], [0, 3, 0], [0, 3, 1], ...]

I can do this as follow:

combinations = []
for i in [0, 1, 2, 3]:
    for j in [0, 1, 2, 3]:
        for k in [0, 1, 2, 3]:
            combinations.append([i, j, k])

I have three for loops because n = 3 and I have [0, 1, 2, 3] in each loop because m = 4.

For more general values of m and n, how can do it?

combinations = []
for i in range(m):
    for j in range(m):
        for k in range(m):
            for l in range(m):
                ... # n loops :(
                   combinations.append([i, j, k, l, ...])
Kira
  • 333
  • 4
  • 11
  • 1
    Another dupe [How can I make a for-loop pyramid more concise in Python?](http://stackoverflow.com/questions/28382433/how-can-i-make-a-for-loop-pyramid-more-concise-in-python). Yet another dupe [Avoiding nested for loops](http://stackoverflow.com/questions/11174745/avoiding-nested-for-loops) – Bhargav Rao Jun 08 '15 at 17:59

1 Answers1

0

itertools.combinations will do.

import itertools

my_list = [1, 2, 3, 4, 5]
for num in range(0, len(my_list)+1):
  for out in itertools.combinations(my_list, num):
     print(out)
Thuruv
  • 78
  • 9