-1

I need to permutate between two arrays.

I don't need all possible combinations, but taking the first element from either of those two vectors and keeping it at the first position. And the same for the other elements as well. I guess the wanted outcome shows it best.

import numpy as np

x = np.array((x1, x2, x3))
y = np.array((y1, y2, y3))

I expect a list with all possibilities which might look like the following:

z = array([[x1, x2, x3], [y1, x2, x3], [x1, y2, x3], [x1, x2, y3], [y1, y2, x3], [x1, y2, y3], [y1, x2, y3], [y1, y2, y3]])

Thanks.

alettmann
  • 21
  • 4
  • Have you tried https://stackoverflow.com/questions/104420/how-to-generate-all-permutations-of-a-list-in-python ? You'll have to adapt it to your 2 arrays case though – Matthias Beaupère Apr 26 '19 at 12:51
  • Possible duplicate of [How to generate all permutations of a list in Python](https://stackoverflow.com/questions/104420/how-to-generate-all-permutations-of-a-list-in-python) – MyNameIsCaleb Apr 26 '19 at 12:52
  • 1
    Just add the two lists and then itertools permutations with r=3 – MyNameIsCaleb Apr 26 '19 at 12:54
  • https://stackoverflow.com/questions/104420/how-to-generate-all-permutations-of-a-list-in-python That one is just setting up all permutations within one list. That is not what I am looking for. I need to keep the positioning of the element and only permutate between the two vectors and from there all possibilities. – alettmann Apr 26 '19 at 12:55

2 Answers2

0

This is how I would approach the problem with itertools.product:

import itertools

data = {
    0: ['x1', 'x2', 'x3'],
    1: ['y1', 'y2', 'y3']}

ans = list()
for comb in itertools.product(range(2), repeat=3):
    # print(comb)
    ans.append([data[key][idx] for idx, key in enumerate(comb)])

ans is:

[['x1', 'x2', 'x3'], ['x1', 'x2', 'y3'], ['x1', 'y2', 'x3'], ['x1', 'y2', 'y3'], ['y1', 'x2', 'x3'], ['y1', 'x2', 'y3'], ['y1', 'y2', 'x3'], ['y1', 'y2', 'y3']]
0

if you have really large lists keep it all in memory could be a problem so is possible to do it using a generator like:

import numpy as np

x = ["x1", "x2", "x3"]
y = ["y1", "y2", "y3"]


def permutations(lists):
    rot = np.rot90(np.array(lists), 3)

    def perms(x, memo=[]):
        """
        returns a generator that permutes all the possible rows
        combinations for a given matrix
        """
        for i in x[0]:

            if len(x) == 1:
                yield memo + [i]
            else:
                yield from perms(x[1:], memo + [i])

    return perms(rot)


for perm in permutations([x, y]):
    print(perm)