I believe what you would want is

- Code: Select all
`r3 = {(u, v) for (u, w1) in r for (w2, v) in r if w1 == w2}`

However, your program runs in quadratic

time complexity so you may want to seek a different solution if you have large inputs. It can be done in linear time.

Also, the time complexity is still poor, but here's a version that uses the same logic plus short circuting

- Code: Select all
`r3 = {(u, v) for (u, v) in r if any(u in pair or v in pair for pair in r)}`

I believe that this version is slightly more readable as well.

For future reference, when you post a problem like this, it's a good idea to post sample input and outputs as well.

Join the #python-forum IRC channel on irc.freenode.net for off-topic chat!

Please prefer not to PM members. The point of the forum is so that anyone can benefit. We don't want to help you over PMs/emails/Skype chats that others can't benefit from