0

My question is similar to this one, but rather I want to find all possible vectors of a given size comprising [x,y,...] elements. For instance, given a list [1,2], how do I find all possible vectors with elements 1 and 2, with size 3? in this case it is:

(1,1,1)
(1,1,2)
(1,2,1)
(2,1,1)
(1,2,2)
(2,1,2)
(2,2,1)
(2,2,2)

What is an elegant way to do this? I'm imagining that subsequent for loops is not the best way to do this. In my real case I am actually looking for $2^{8}$ combinations since I am looking for vectors with 8 elements.

Sos
  • 1,783
  • 2
  • 20
  • 46

2 Answers2

0

Thanks to the comments above, I got it working like so:

[x for x in itertools.product(*[x for x in ((1,2),)*3])]
#out:
[(1, 1, 1),
 (1, 1, 2),
 (1, 2, 1),
 (1, 2, 2),
 (2, 1, 1),
 (2, 1, 2),
 (2, 2, 1),
 (2, 2, 2)]
Sos
  • 1,783
  • 2
  • 20
  • 46
0

The following does the work (it works well with 8 elemements too):

l=sum([list(set(itertools.permutations(i))) for i in list(itertools.combinations_with_replacement([1,2], 3))], [])
print(l)

Output:

[(1, 1, 1), (1, 2, 1), (2, 1, 1), (1, 1, 2), (1, 2, 2), (2, 2, 1), (2, 1, 2), (2, 2, 2)]
IoaTzimas
  • 10,538
  • 2
  • 13
  • 30