Using itertools.product repeat multiple times

Viewed 344

I am trying to generate a list of unique lists each 5 elements long, the order is not important but there can't be any repeated elements. The first 3 elements needs to be from [1,2,3,4] and elements 4 and 5 from [5,6,7,8]. for example [1,2,3,7,8] is valid but [1,2,2,7,8] is not nor is [1,2,7,8,9]

The below code works but I am wondering is there a better way of incorporating the product function? something like d = product([L1, repeat=3][L4,repeat=2). From reading the docs the repeat keyword can only be used once, like this: d = product(L1,L4,repeat=2).

Any ideas how i could do this?

Thanks

   from itertools import product

    L1 = [1,2,3,4]
    L2 = [1,2,3,4]
    L3 = [1,2,3,4]
    L4 = [5,6,7,8]
    L5 = [5,6,7,8]

    d = product(L1,L2,L3,L4,L5)


    result=[]

    for x in d:
        if x.count(1)<2 and x.count(2)<2 and x.count(3)<2 and x.count(4)<2 and x.count(5)<2 and x.count(6)<2 and x.count(7)<2 and x.count(8)<2:
            result.append(sorted(x))

    result2 = []
    for x in result:
        if x not in result2:
            result2.append(x)
    
    print(result2)


result2
[[1, 2, 3, 5, 6],
 [1, 2, 3, 5, 7],
 [1, 2, 3, 5, 8],
 [1, 2, 3, 6, 7],
 [1, 2, 3, 6, 8],
 [1, 2, 3, 7, 8],
 [1, 2, 4, 5, 6],
 [1, 2, 4, 5, 7],
 [1, 2, 4, 5, 8],
 [1, 2, 4, 6, 7],
 [1, 2, 4, 6, 8],
 [1, 2, 4, 7, 8],
 [1, 3, 4, 5, 6],
 [1, 3, 4, 5, 7],
 [1, 3, 4, 5, 8],
 [1, 3, 4, 6, 7],
 [1, 3, 4, 6, 8],
 [1, 3, 4, 7, 8],
 [2, 3, 4, 5, 6],
 [2, 3, 4, 5, 7],
 [2, 3, 4, 5, 8],
 [2, 3, 4, 6, 7],
 [2, 3, 4, 6, 8],
 [2, 3, 4, 7, 8]]
1 Answers

I would instead use itertools.combinations in combination with itertools.product:

from itertools import chain, combinations, product

result = list(
    map(
        list,
        map(
            chain.from_iterable,
            product(
                combinations([1, 2, 3, 4], 3),
                combinations([5, 6, 7, 8], 2),
            ),
        ),
    ),
)
Related