pythoncombinations

All combinations of elements in a vector in a larger vector


I have the following input vector.

['a','b','c'] 

I want to list all possible combinations.

There are three restrictions:

Two permissions:

Given this input vector above, the only valid outputs are the following (I might have missed one or two but you get the idea):

[' ',' ',' ','a','b','c'],
[' ',' ','a',' ','b','c'],
[' ','a',' ',' ','b','c'],
['a',' ',' ',' ','b','c'],
[' ',' ','a','b',' ','c'],
[' ','a','b',' ',' ','c'],
['a','b',' ',' ',' ','c'],
[' ','a',' ','b',' ','c'],
['a',' ','b',' ',' ','c'],
['a',' ',' ','b',' ','c'],
[' ',' ','a','b','c',' '],
[' ','a','b','c',' ',' '],
['a','b','c',' ',' ',' '],
[' ','a',' ','b','c',' '],
['a',' ','b','c',' ',' '],
['a',' ','b',' ','c',' ']

My first idea was to generate circa 6! vectors where the vectors are random combinations of the possible values, including the empty value: [abc ]|[abc ]...[abc ] and then remove all vectors where a/b/c occur more than they do in the input vector and the order of abc is not the same as in the input vector. But this brute force measure would take ages.

I'll have to do this a lot, and for input vectors and output vectors of varying sizes.


Solution

  • Choosing 3 out of the 6 indices and placing the elements there:

    from itertools import combinations
    
    v = ['a','b','c']
    n = 6
    
    for I in combinations(range(n), len(v)):
        out = [' '] * n
        for i, out[i] in zip(I, v):
            pass
        print(out)