Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

eliminating redundant tuples

Tags:

python

tuples

If I have a list of tuples, where each tuple represents variables, a, b and c, how can I eliminate redundant tuples?

Redundant tuples are those where a and b are simply interchanged, but c is the same. So for this example:

tups = [(30, 40, 50), (40, 30, 50), (20, 48, 52), (48, 20, 52)]

my final list should only contain only half of the entries. One possible output:

tups = [(30, 40, 50), (20, 48, 52)]

another

tups = [(40, 30, 50), (20, 48, 52)]

etc.

Is there an easy Pythonic way to do this?

I tried using sets, but (30, 40, 50) is different from (40, 30, 50), but to me these are redundant and I'd just like to keep one of them (doesn't matter which, but if I could pick I'd prefer the low to high value order). If there was a way to sort the first 2 elements of the tuples, then using the set would work.

I am sure I could hack together a working solution (perhaps converting tuples to lists as intermediate step), but I just wanted to see if there's an easy and obvious way to do this that I'm not familiar with.

PS: This question partially motivated by PE #39. But even aside from this PE problem, I am now just curious how this could be done easily (or if).

Edit:

Just to provide a bit of context for those not familiar with PE #39 - a, b, and c represent sides of a right triangle, so I'm checking if a**2 + b**2 == c**2, clearly the order of a and b don't matter.

like image 875
Levon Avatar asked Jul 28 '12 23:07

Levon


2 Answers

set([(a,b,c) if a<b else (b,a,c) for a,b,c in tups])
like image 116
tzelleke Avatar answered Oct 12 '22 02:10

tzelleke


From your question, it seems that the first two elements of your tuples form a sub-unit within the tuple. Therefore it would seem to make sense to restructure your data as a tuple of a tuple and a third number, where the first tuple is the first two numbers in sorted order. Then you can naturally use sets:

>>> newTups = [(tuple(sorted([a, b])), c) for a, b, c in tups]
>>> newTups
[((30, 40), 50), ((30, 40), 50), ((20, 48), 52), ((20, 48), 52)]
>>> set(newTups)
set([((20, 48), 52), ((30, 40), 50)])
like image 24
BrenBarn Avatar answered Oct 12 '22 02:10

BrenBarn