Ask Your Question
0

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

asked 2022-05-16 14:30:00 +0200

vidyarthi gravatar image

updated 2022-05-16 23:57:03 +0200

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 flag offensive close merge delete

Comments

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

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

(I edited, changing 1 to l.)

John Palmieri gravatar imageJohn Palmieri ( 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...)

dan_fulea gravatar imagedan_fulea ( 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...

John Palmieri gravatar imageJohn Palmieri ( 2022-05-18 01:12:56 +0200 )edit

2 Answers

Sort by ยป oldest newest most voted
2

answered 2022-05-16 21:55:49 +0200

tmonteil gravatar image

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))]
edit flag offensive delete link more
0

answered 2022-05-18 16:26:48 +0200

Max Alekseyev gravatar image

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

t = ['a','b','c','d']
for p in Permutations(t):
    print(p)
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2022-05-16 14:30:00 +0200

Seen: 208 times

Last updated: May 18 '22