-1

I need to build a function that takes in 2 tuples, and pairs them to all the pairs possible.

for example i need to take to tuples:

first_tuple = (1, 2)
second_tuple = (4, 5)

and the result need to be:

((1, 4), (4, 1), (1, 5), (5, 1), (2, 4), (4, 2), (2, 5), (5, 2))
GhostCat
  • 137,827
  • 25
  • 176
  • 248
maya_mov
  • 35
  • 4
  • Please take out some time in reading existing answers in the linked duplicate and try applying it to your problem – Sheldore May 07 '19 at 07:56

3 Answers3

7

You can use itertools.product and itertools.chain, the idea is to take all posible product orderings and since the tuples have size 2 you just need to flip them:

>>> from itertools import product, chain
>>> first_tuple = (1, 2)
>>> second_tuple = (4, 5)
>>> half = list(product(first_tuple, second_tuple))
>>> half
[(1, 4), (1, 5), (2, 4), (2, 5)]
>>> list(chain(half, map(lambda x: (x[1], x[0]), half)))
[(1, 4), (1, 5), (2, 4), (2, 5), (4, 1), (5, 1), (4, 2), (5, 2)]

For an arbitrary tuple size you can use (@Aran-Fei idea):

[perm for tup in half for perm in itertools.permutations(tup)]
Netwave
  • 40,134
  • 6
  • 50
  • 93
  • 2
    The last line can be changed to `[perm for tup in half for perm in itertools.permutations(tup)]` if you want to support an arbitrary number of input tuples instead of just two. – Aran-Fey May 07 '19 at 08:00
3

You first start by creating the initial pairing using itertools.product, and then use that pairing to create another pairing where the tuple elements are swapped

from itertools import product
first_tuple = (1, 2)
second_tuple = (4, 5)

#First pairing
prod_1 = list(product(first_tuple, second_tuple))

#Pairing with swapped positions of tuple
prod_2 = [(t[1], t[0]) for t in prod_1]

#Final output
res = prod_1 + prod_2
print(res)

The output will be

[(1, 4), (1, 5), (2, 4), (2, 5), (4, 1), (5, 1), (4, 2), (5, 2)]
Devesh Kumar Singh
  • 20,259
  • 5
  • 21
  • 40
0
from itertools import chain,product

first_tuple = (1, 2)
second_tuple = (4, 5)

combined = list(chain(*[[(f,s),(s,f)] for f in first_tuple for s in second_tuple]))
print (combined)

output:

[(1, 4), (4, 1), (1, 5), (5, 1), (2, 4), (4, 2), (2, 5), (5, 2)]

.

itertools.product()

This tool computes the cartesian product of input iterables. It is equivalent to nested for-loops. For example, product(A, B) returns the same as ((x,y) for x in A for y in B).

To get first part of desired list is:

list(product(first_tuple, second_tuple)) # (1, 4), (4, 1), (1, 5), (5, 1)

for the second part is enough to reverse:

list(product(second_tuple, first_tuple)) # (2, 4), (4, 2), (2, 5), (5, 2)

.

combined1 = list(product(first_tuple, second_tuple)) + list(product(second_tuple, first_tuple))
print (combined1)

output:

[(1, 4), (1, 5), (2, 4), (2, 5), (4, 1), (4, 2), (5, 1), (5, 2)]
ncica
  • 7,015
  • 1
  • 15
  • 37