0

How to generate permutations of n variables given the domain of each variable. (in python)

I know about itertools, but that requires a fixed domain for the permutations so that won't work. Also is there a python library that does this? Thanks.

Basically: Given 3 variables: A with Domain (2,3) B with Domain (1) C with Domain (1,2,3)

How do you generate all permutations of ABC?

2,1,1
3,1,1
2,1,2
3,1,2
2,1,3
3,1,3
2
  • You mean combinations, not permutations? Commented Feb 28, 2016 at 1:02
  • 3
    I think OP meant the cartesian product Commented Feb 28, 2016 at 1:10

3 Answers 3

5
>>> list(itertools.product((2, 3), (1,), (1, 2, 3)))
[(2, 1, 1), (2, 1, 2), (2, 1, 3), (3, 1, 1), (3, 1, 2), (3, 1, 3)]
Sign up to request clarification or add additional context in comments.

Comments

1

The itertools.product function does not require "fixed domain" as you state, nor do any functions.

For example this code does what you want:

a = [2, 3]
b = [1]
c = [1, 2, 3]
print(itertools.product(a, b, c))

and would do the same for any set of sequences of any length.

Comments

1

itertools.product has been duly suggested and works fine for the problem at hand. If you are - if only for academic reasons - interested in a sample implementation, here's a generator function:

def cartesian_product(*lists):  # lists can really be any sequences
    if any([not l for l in lists]):  # c.p. is empty if any list is empty
        return

    n = len(lists)
    indexes = [0] * n

    while True:
        yield tuple(lists[i][indexes[i]] for i in xrange(n))  # currently indexed element of each list
        # update indexes
        for i in xrange(n-1, -1, -1):  # loop through indexes from back
            if indexes[i] < len(lists[i]) - 1:      # stop at first index that can be incremented ...
                indexes[i] += 1                     # ... increment it ...
                indexes[i+1:n] = [0] * (n - i - 1)  # ... reset all succeeding indexes to 0
                break
        else:  # no index could be incremented -> end
            break

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.