Reputation: 1183
I just can't come up with a way to solve my problem: x is an integer. I want a list of all possibles combinations of x-tuples where those tuples' elements are in range from 0 to x (excluding x).
So if x = 3
I have 3^3 combinations: [(0,0,0),(0,0,1),(0,0,2),(0,1,0),(0,1,1),(0,1,2),(0,2,0),(0,2,1),(0,2,2),(1,0,0),(1,0,1),(1,0,2),(1,1,0),(1,1,1),(1,1,2),(1,2,0),(1,2,1),(1,2,2),(2,0,0),(2,0,1),(2,0,2),(2,1,0),(2,1,1),(2,1,2),(2,2,0),(2,2,1),(2,2,2)]
.
If x = 4
I would have 4^4 combinations with 4-tuples where the elements of those tuples are in {0,1,2,3}.
Upvotes: 0
Views: 1686
Reputation: 13195
Ok, not permatations, but permutations with repeats perhaps.
Anyway, itertools.product()
is doing that:
list(itertools.product([0,1,2],repeats=3))
result:
[(0, 0, 0), (0, 0, 1), (0, 0, 2), (0, 1, 0), (0, 1, 1), (0, 1, 2), (0, 2, 0), (0, 2, 1), (0, 2, 2), (1, 0, 0), (1, 0, 1), (1, 0, 2), (1, 1, 0), (1, 1, 1), (1, 1, 2), (1, 2, 0), (1, 2, 1), (1, 2, 2), (2, 0, 0), (2, 0, 1), (2, 0, 2), (2, 1, 0), (2, 1, 1), (2, 1, 2), (2, 2, 0), (2, 2, 1), (2, 2, 2)]
oh it's a dupe. But I found it too :-)
(Side remark: combinations are about subsets, and thus order of elements does not matter to them)
Upvotes: 0
Reputation: 1299
I think it's just a list comprehension:
mylist = [(x,y,z) for x in range(3) for y in range(3) for z in range(3)]
Note that using itertools.permutations(range(3)) doesn't generate duplicates, just the permutations of the set (0, 1, 2). I.e. you won't get (1, 1, 2), etc.
Upvotes: 1
Reputation: 24052
Here's the proper way to use itertools
to get what you want:
list(itertools.product(range(3), repeat=3))
The output is:
[(0, 0, 0), (0, 0, 1), (0, 0, 2), (0, 1, 0), (0, 1, 1),
(0, 1, 2), (0, 2, 0), (0, 2, 1), (0, 2, 2), (1, 0, 0),
(1, 0, 1), (1, 0, 2), (1, 1, 0), (1, 1, 1), (1, 1, 2),
(1, 2, 0), (1, 2, 1), (1, 2, 2), (2, 0, 0), (2, 0, 1),
(2, 0, 2), (2, 1, 0), (2, 1, 1), (2, 1, 2), (2, 2, 0),
(2, 2, 1), (2, 2, 2)]
Of course, this can scale up by using values other than 3. In general:
list(itertools.product(range(x), repeat=x))
will work for any x
.
Upvotes: 2