1

I would like to generate combinations of length k, from a set of N numbers, where order matters and numbers can be replaced. For example if k = 3, and N = [1, 2, 3], then candidate outputs would include, for example, (1, 1, 1), (2, 2, 2), (3, 2, 1), (1, 2, 3).

I believe I'm nearly there with the following code

x = list(itertools.combinations_with_replacement(range(1,4),3)

But this gives results where order does not matter - i.e it thinks (1, 2, 3) is the same as (3, 2, 1), (2, 3, 1) etc etc.

Any help much appreciated!

MarcelKlockman
  • 117
  • 3
  • 12

2 Answers2

3

What you need is product

import itertools

N = [1, 2, 3]

y = list(itertools.product(N, N))
print(y)  # [(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]
          #             ^               ^
          #             |_______________| he no longer thinks it's the same

Now, from your question it is not clear what you would like to do if k != len(N) so I will leave that to you (slice N maybe?)..

Ma0
  • 15,057
  • 4
  • 35
  • 65
1

Try this:

import itertools
x = [1, 2, 3]
list(itertools.product(x, repeat=3))
Kewl
  • 3,327
  • 5
  • 26
  • 45
  • Just puts it in a list. Probably better to do it with list(itertools.product(x, repeat=3)), editing that now – Kewl Mar 06 '17 at 13:37
  • 2
    In recent versions of Python you can do it with `[*itertools.product(x, repeat=3)]` – PM 2Ring Mar 06 '17 at 13:39