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.

Due to the reasons discussed

here we will be moving to

python-forum.io on October 1, 2016.

This forum will be locked down and no one will be able to post/edit/create threads, etc. here from thereafter. Please create an account at the new site to continue discussion.