i want to define a function that returns all the possible pairing of two giving tuples (including backwards). im new to python and having difficlty writing the correct function.
its supposed to look like this:
>>> first_tuple = (1, 2)
>>> second_tuple = (4, 5)
>>> mult_tuple(first_tuple, second_tuple)
((1, 4), (4, 1), (1, 5), (5, 1), (2, 4), (4, 2), (2, 5), (5, 2))
this is what i wrote and it doesnt work in any scenerio:
def mult_tuple(tuple1, tuple2):
sofit = []
for x in tuple1:
for y in tuple2:
sofit.append(x, y)
sofit.append(y, x)
return sofit
I WOULD APPRICIATE YOUR HELP
forgive my english
THANK YOU!
CodePudding user response:
You could use itertools.product
and zip
:
from itertools import product
def mult_tuple(a: tuple[int, ...], b: tuple[int, ...]) -> tuple[tuple[int, ...], ...]:
return tuple(t for p in zip(product(a, b), product(b, a)) for t in p)
# If you want to remove duplicates use below:
# return tuple(set((t for p in zip(product(a, b), product(b, a)) for t in p)))
first_tuple = (1, 2)
second_tuple = (4, 5)
print(mult_tuple(first_tuple, second_tuple))
Output:
((1, 4), (4, 1), (1, 5), (4, 2), (2, 4), (5, 1), (2, 5), (5, 2))
CodePudding user response:
You're almost there, note that append takes one argument so you need to pass the pair as a tuple:
first_tuple = (1, 2)
second_tuple = (4, 5)
def mult_tuple(tuple1, tuple2):
sofit = []
for x in tuple1:
for y in tuple2:
sofit.append((x, y))
sofit.append((y, x))
return sofit
answer = mult_tuple(first_tuple, second_tuple)
print(answer)
output:
[(1, 4), (4, 1), (1, 5), (5, 1), (2, 4), (4, 2), (2, 5), (5, 2)]
CodePudding user response:
Since @ItayB has already answered your question about the algorithm, I am going to give you another way to do it.
The itertools
module consists of many useful functions, one of which is combinations()
The code:
tuple(
set(
list(combinations(first_tuple second_tuple, 2))
list(combinations(reversed(first_tuple second_tuple), 2))
)
)
We run it reversed as well because your requirement specifically asks for both (1,5) and (5,1). Another approach could've been to use list comprehension to reverse the tuples, an exercise I am leaving to OP.
Admittedly, this is a poor use of the function, especially because of the syntax. I am sure somebody could point out some improvements. But the point was to introduce the very helpful itertools.