listing all those pairs of tuples which are permutations of each other

Suppose I have a list of tuples like

import itertools
l=range(0,6)
m=itertools.combinations(l,2)
list(m)


How do I get those pairs of tuples (i,j);(x,y) such that (i,j)=(y,x)? Also, is there a way to generalize this, that is, I would to have pairs of tuples (a,b,c,...);(x,y,z...) such that (a,b,c...)=(z,y,x...). Is there any efficent way of doing this? Thanks beforehand.

edit retag close merge delete

I guess itertools.combinations(1,2) should be replaced by itertools.combinations(l,2).

( 2022-05-16 21:48:28 +0200 )edit

(I edited, changing 1 to l.)

( 2022-05-16 23:57:34 +0200 )edit

Please never use a single ell-letter for the name of a variable, even if it stays for a list. (In our case it is a range...)

( 2022-05-17 22:35:57 +0200 )edit

@dan_fulea: next you're probably going to suggest that we shouldn't use "O" for a variable, either...

( 2022-05-18 01:12:56 +0200 )edit

Sort by ยป oldest newest most voted

I am not sure to understand your question, but you can do:

sage: [((a,b),(b,a)) for (a,b) in m]
[((0, 1), (1, 0)),
((0, 2), (2, 0)),
((0, 3), (3, 0)),
((0, 4), (4, 0)),
((0, 5), (5, 0)),
((1, 2), (2, 1)),
((1, 3), (3, 1)),
((1, 4), (4, 1)),
((1, 5), (5, 1)),
((2, 3), (3, 2)),
((2, 4), (4, 2)),
((2, 5), (5, 2)),
((3, 4), (4, 3)),
((3, 5), (5, 3)),
((4, 5), (5, 4))]


If you have longer tuples, you can reverse them as follows:

sage: t = (1,2,5,6)
sage: t[::-1]
(6, 5, 2, 1)


So, you can do :

sage: m=itertools.combinations(l,4)
sage: [(t,t[::-1]) for t in m]
[((0, 1, 2, 3), (3, 2, 1, 0)),
((0, 1, 2, 4), (4, 2, 1, 0)),
((0, 1, 2, 5), (5, 2, 1, 0)),
((0, 1, 3, 4), (4, 3, 1, 0)),
((0, 1, 3, 5), (5, 3, 1, 0)),
((0, 1, 4, 5), (5, 4, 1, 0)),
((0, 2, 3, 4), (4, 3, 2, 0)),
((0, 2, 3, 5), (5, 3, 2, 0)),
((0, 2, 4, 5), (5, 4, 2, 0)),
((0, 3, 4, 5), (5, 4, 3, 0)),
((1, 2, 3, 4), (4, 3, 2, 1)),
((1, 2, 3, 5), (5, 3, 2, 1)),
((1, 2, 4, 5), (5, 4, 2, 1)),
((1, 3, 4, 5), (5, 4, 3, 1)),
((2, 3, 4, 5), (5, 4, 3, 2))]

more

If you want permutations, then you can use Permutations generator:

t = ['a','b','c','d']
for p in Permutations(t):
print(p)

more