Search code examples
pythonlistcombinationssliding-window

Python - Increasing combinations of two lists


I'm trying to create combinations of two lists. List A should be increasing, or a sliding window if you will. List B is static. Where List A can have any number of values.

My question seems to be a different than what I see already posted, as I am using a sliding window on one list and keeping the other list static, so it's not as simple as every combination of both lists.

So the inputs it would look like the below:

ListA = [Val1, Val2, Val3]
ListB = [0, 1]

Giving the below output:

[Val1, 0]
[Val1, 1]
[Val2, 0]
[Val2, 1]
[Val3, 0]
[Val3, 1]

[[Val1, 0], [Val2, 0]]
[[Val1, 0], [Val2, 1]]
[[Val1, 1], [Val2, 0]]
[[Val1, 1], [Val2, 1]]

[[Val1, 0], [Val3, 0]]
[[Val1, 0], [Val3, 1]]
[[Val1, 1], [Val3, 0]]
[[Val1, 1], [Val3, 1]]

[[Val2, 0], [Val3, 0]]
[[Val2, 0], [Val3, 1]]
[[Val2, 1], [Val3, 0]]
[[Val2, 1], [Val3, 1]]

[[Val1, 0], [Val2, 0], [Val3, 0]]
[[Val1, 0], [Val2, 0], [Val3, 1]]
[[Val1, 0], [Val2, 1], [Val3, 0]]
[[Val1, 0], [Val2, 1], [Val3, 1]]
[[Val1, 1], [Val2, 0], [Val3, 0]]
[[Val1, 1], [Val2, 0], [Val3, 1]]
[[Val1, 1], [Val2, 1], [Val3, 0]]
[[Val1, 1], [Val2, 1], [Val3, 1]]

I've been experimenting with itertools combinations and product for a while now, I cannot get my head around it. Covid brain fog :D. Any help would be appreciated.

Thanks


Solution

  • I imagine there's a cleaner way to do this, but this works.

    from itertools import chain, combinations, product
    
    A = ['v1', 'v2', 'v3']
    B = [0, 1]
    
    for i in chain.from_iterable(combinations(A, k+1) for k in range(len(A))):   
        print([list(zip(i,j)) for j in product(B,repeat=len(i))])
    
    print()
    

    In the for loop, we loop over the powerset of A (excluding the empty set). So (v1), (v2), (v3), (v1,v2), (v1,v3), (v2,v3), (v1,v2,v3).

    product(B,repeat=len(i)) is all permutations (allowing repeats) of elements of B of len(i). So if i = (v1,v2), we would get ((0,0),(0,1),(1,0),(1,1)).

    Finally, loop through those permutations and zip each one with i. Repeat for all elements of the powerset.