S L
S L

Reputation: 14328

generating list with permuted tuples in a list

How to permute the tuple on a list.

A= [(a,b), (c,d), (e, f)]

If A is a list then with permutation tuples, the list are

  [(a,b), (c,d), (e, f)]
  [(a,b), (c,d), (f, e)]
  [(a,b), (d,c), (e, f)]
  [(a,b), (d,e), (f, e)]
  ....

It has 8 such list.

Upvotes: 0

Views: 325

Answers (2)

Leonardo.Z
Leonardo.Z

Reputation: 9801

from itertools import chain, permutations

A = [('a', 'b'), ('c', 'd'), ('e', 'f')]

print map(lambda x: zip(*[iter(x)]*2),permutations(chain(*A)))

# Hints:
# chain(*A) => ['a', 'b', 'c', 'd', 'e', 'f']

# permutations(chain(*A)) => ('a', 'b', 'c', 'd', 'e', 'f'), 

#                            ('a', 'b', 'c', 'd', 'f', 'e'), 

#                            ('a', 'b', 'c', 'e', 'd', 'f'),
                             ...
# lambda x: zip(*[iter(x)]*2) chunks the iterable by length 2

# [iter(x)]*2 creates a list contains 2 references to a same iterator object.

# The left-to-right evaluation order of the iterables is guaranteed.                   
# This makes possible an idiom for clustering a data series 
# into n-lengthgroups using zip(*[iter(s)]*n).

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1124968

Use itertools.product() with a generator expression to generate the inversions:

>>> from itertools import product
>>> A = [('a', 'b'), ('c', 'd'), ('e', 'f')]
>>> for perm in product(*((l, l[::-1]) for l in A)):
...     print perm
... 
(('a', 'b'), ('c', 'd'), ('e', 'f'))
(('a', 'b'), ('c', 'd'), ('f', 'e'))
(('a', 'b'), ('d', 'c'), ('e', 'f'))
(('a', 'b'), ('d', 'c'), ('f', 'e'))
(('b', 'a'), ('c', 'd'), ('e', 'f'))
(('b', 'a'), ('c', 'd'), ('f', 'e'))
(('b', 'a'), ('d', 'c'), ('e', 'f'))
(('b', 'a'), ('d', 'c'), ('f', 'e'))

The ((l, l[::-1]) for l in A) generator expression produces 3 arguments to product(), each a tuple consisting of both a sublist and the inversion of that sub list of A:

>>> [(l, l[::-1]) for l in A]
[(('a', 'b'), ('b', 'a')), (('c', 'd'), ('d', 'c')), (('e', 'f'), ('f', 'e'))]

Upvotes: 5

Related Questions