Search code examples
pythonlisttuplespermutation

How to print all the permutations of two lists in a custom format?


P = [(2, 2, 3), (2, 3, 2), (3, 2, 2)]

X = [[(1, 2, 4), (1, 4, 2), (2, 1, 4), (2, 4, 1), (4, 1, 2), (4, 2, 1)], [(1, 2, 6), (1, 6, 2), (2, 1, 6), (2, 6, 1), (6, 1, 2), (6, 2, 1)], [(1, 3, 6), (1, 6, 3), (3, 1, 6), (3, 6, 1), (6, 1, 3), (6, 3, 1)]]

How can I print all the permutations of the above 2 lists in the form:

P1(X1) P2(x2) P3(x3)

for example:

2(1) 2(2) 3(4),
2(1) 2(4) 3(2),
2(2) 2(1) 3(4) and so on

i.e. first tuple from P combines with all tuples of X then second tuple of P combines with all tuples of X and so on.


Solution

  • you could use itertools.product and zip this way:

    from itertools import product
    
    P = [(2, 2, 3), (2, 3, 2), (3, 2, 2)]
    
    X = [[(1, 2, 4), (1, 4, 2), (2, 1, 4), (2, 4, 1), (4, 1, 2), (4, 2, 1)],
         [(1, 2, 6), (1, 6, 2), (2, 1, 6), (2, 6, 1), (6, 1, 2), (6, 2, 1)],
         [(1, 3, 6), (1, 6, 3), (3, 1, 6), (3, 6, 1), (6, 1, 3), (6, 3, 1)]]
    
    for p, xs in product(P, X):
        for x in xs:
            print(" ".join(f"{a}({b})" for a, b in zip(p, x)))
    

    this outputs

    2(1) 2(2) 3(4)
    2(1) 2(4) 3(2)
    2(2) 2(1) 3(4)
    2(2) 2(4) 3(1)
    2(4) 2(1) 3(2)
    2(4) 2(2) 3(1)
    2(1) 2(2) 3(6)
    2(1) 2(6) 3(2)
    2(2) 2(1) 3(6)
    ...