-1

I have this code:

from itertools import permutations

lizt = [(1,2,3), (1,3,4), (6,5,3), (2,5,3), (1,6,2), (4,1,6)]

lizt = list(permutations(lizt, 3))

for i in lizt:
    print(i)
    print(' ')

But I want to print out the possible permutation only if the numbers 1-6 exist somewhere in one of the three tuples.

For instance, I want this:

((1, 6, 2), (2, 5, 3), (4, 1, 6))

bcause it has all numbers somewhere in there, but I dont want this:

((1, 2, 3), (1, 3, 4), (1, 6, 2))

because it is missing the 5. How can I do this?

1 Answers1

1

You can filter the lists by building a set of all values they contain, and checking that the length of this set is 6:

from itertools import permutations, chain

lizt = [(1,2,3), (1,3,4), (6,5,3), (2,5,3), (1,6,2), (4,1,6)]
valid = [perm for perm in permutations(lizt, 3) if len(set(chain.from_iterable(perm))) == 6]

for i in valid:
    print(i)

Output:

((1, 2, 3), (1, 3, 4), (6, 5, 3))
((1, 2, 3), (6, 5, 3), (1, 3, 4))
((1, 2, 3), (6, 5, 3), (4, 1, 6))
((1, 2, 3), (2, 5, 3), (4, 1, 6))
((1, 2, 3), (4, 1, 6), (6, 5, 3))
((1, 2, 3), (4, 1, 6), (2, 5, 3))
((1, 3, 4), (1, 2, 3), (6, 5, 3))
((1, 3, 4), (6, 5, 3), (1, 2, 3))
((1, 3, 4), (6, 5, 3), (2, 5, 3))
... and so on

chain.from_iterable(perm) yields all the values from the tuples in perm.

Thierry Lathuille
  • 23,663
  • 10
  • 44
  • 50