Unique combinations of length 2^N of four elements with constraints

19 hours ago 1
ARTICLE AD BOX

Each sequence you want is really just two independent sequences (one with elements from each group) interleaved with each other. As such, you can do this by finding all the n-length sequences for each group independently, then finding the ways to take one sequence from every group, then properly interleaving the sequences for each combination.

This solution uses itertools and zip, so it'll work lazily:

from collections.abc import Iterable import itertools def constrained_combinations[T](groups: Iterable[Iterable[T]], n_chunks: int) -> Iterable[Iterable[T]]: subsequences = (itertools.product(group, repeat=n_chunks) for group in groups) uninterleaved_sequences = itertools.product(*subsequences) return (itertools.chain(*zip(*sequence)) for sequence in uninterleaved_sequences) for sequence in constrained_combinations(("AB", "XY"), 3): print(list(sequence)) """ ['A', 'X', 'A', 'X', 'A', 'X'] ['A', 'X', 'A', 'X', 'A', 'Y'] ['A', 'X', 'A', 'Y', 'A', 'X'] ... ['B', 'Y', 'B', 'X', 'B', 'Y'] ['B', 'Y', 'B', 'Y', 'B', 'X'] ['B', 'Y', 'B', 'Y', 'B', 'Y'] """

I'm not sure why you need the 2^n part, but presumably there's a good reason. You can get that by messing with the number of chunks:

def ab_xy(n: int) -> Iterable[Iterable[str]]: return constrained_combinations(("AB", "XY"), 2**(n-1)) for sequence in ab_xy(3): print(list(sequence)) """ ['A', 'X', 'A', 'X', 'A', 'X', 'A', 'X'] ['A', 'X', 'A', 'X', 'A', 'X', 'A', 'Y'] ['A', 'X', 'A', 'X', 'A', 'Y', 'A', 'X'] ... ['B', 'Y', 'B', 'Y', 'B', 'X', 'B', 'Y'] ['B', 'Y', 'B', 'Y', 'B', 'Y', 'B', 'X'] ['B', 'Y', 'B', 'Y', 'B', 'Y', 'B', 'Y'] """
Read Entire Article