Reputation: 2911
Say I have 3 parameters: a range, size of n-element tuples (actually it might also be a list) and possible combinations (without or with repetition). I want to get all the possible combinations of the numbers from the range.
So for example:
without repetitions
the result would be:
(1, 1)(1, 2)(1, 3)(1, 4)(1, 5) (2, 1)(2, 2)(2, 3)(2, 4)(2, 5) (3, 1)(3, 2)(3, 3)(3, 4)(3, 5) (4, 1)(4, 2)(4, 3)(4, 4)(4, 5) (5, 1)(5, 2)(5, 3)(5, 4)(5, 5)
With repetitions there would be of course much more tuples.
It can be done iteratively obviously, but what would be the more pythonic and elegant way of achieving this task (maybe additional tools)?
Upvotes: 1
Views: 953
Reputation: 666
With repetitions:
>>> from itertools import product
>>> list(product(range(1, 6), repeat=2))
[(1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (2, 1), (2, 2), (2, 3), (2, 4), (2, 5), (3, 1), (3, 2), (3, 3), (3, 4), (3, 5), (4, 1), (4, 2), (4, 3), (4, 4), (4, 5), (5, 1), (5, 2), (5, 3), (5, 4), (5, 5)]
Without repetitions:
>>> from itertools import permutations
>>> list(permutations(range(1, 6), 2))
[(1, 2), (1, 3), (1, 4), (1, 5), (2, 1), (2, 3), (2, 4), (2, 5), (3, 1), (3, 2), (3, 4), (3, 5), (4, 1), (4, 2), (4, 3), (4, 5), (5, 1), (5, 2), (5, 3), (5, 4)]
Upvotes: 6