1

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:

  • Range a..b = 1..5
  • size of tuple s=2
  • 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)?

1
  • You say your example result is without repetitions, but it contains (1, 1), (2, 2), etc. It also has (1, 2) and (2, 1), so that's not the definition of repetitions you're using. What would the version with repetitions look like? Commented Jun 28, 2019 at 17:31

1 Answer 1

6

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)]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.