Possible Duplicate:

How can I remove B -> A from a list if A -> B is in the list?

Delete duplicate elements from list

Pattern matching deletion of list items

How do I delete the duplicates of a set who’s elements are themselves sets?

Here is an example:

Deleting the duplicates from {{x,y},{y,x}} should give {{x,y}} (or {{y,x}}, both answers are equivalent).

I am particularly interested in the case when x and y are lists, but a solution that works for x and y of any type would be better.

=================

=================

2 Answers

2

=================

Does

DeleteDuplicates[Sort /@ {{2, 1}, {1, 2}}]

help?

Edit : ( Just try your data – Mathematica is cool, isn’t it ? )

DeleteDuplicates[Sort /@ {{x, y}, {y, x}}]

Sorry for the misleading example. I clarified the question and example to make it clear that the elements of the inner sets are not integers.

– Tyson Williams

Jun 29 ’12 at 19:36

Just try it with your data.

– user21

Jun 29 ’12 at 19:45

Weird, I had tried it, but I thought it gave me the wrong answer. It is working now though, so thanks!

– Tyson Williams

Jun 29 ’12 at 19:47

I see. I think the order of operations tricked me and it executed the Sort /@ part sooner than I wanted. Adding parentheses to force the correct order fixed that.

– Tyson Williams

Jun 29 ’12 at 19:50

Glad you could figure it out.

– user21

Jun 29 ’12 at 19:51

Here is another solution based on Union and its option SameTest :

Union[{{x, y}, {y, x}}, SameTest -> (Union[#1] == Union[#2] &)]

{{x, y}}

Union[{{2, 1}, {1, 2}, {3, 1}}, SameTest -> (Union[#1] == Union[#2] &)]

{{1, 2}, {3, 1}}

In case of more nested lists I would use Flatten on appropriate level, e.g.

Union @ Flatten[{ {{2, 1}}, {{1, 2}} }, 2]

{1, 2}

where DeleteDuplicates[Sort /@ { {{2, 1}}, {{1, 2}} }] does not work if we don’t use Flatten. However, this is not a general solution, one has to consider appropriate examples and work on case by case basis.

Sorry for the misleading example. I clarified the question and example to make it clear that the elements of the inner sets are not integers.

– Tyson Williams

Jun 29 ’12 at 19:38

1

Pardon me but this does not delete duplicate sets: deleting duplicates from {{2, 1}, {1, 2}, {3, 1}} should result in {{1,2}, {1,3}}, as those are the two distinct sets, but Union@Flatten[{{2, 1}, {1, 2}, {3, 1}}] returns {1, 2, 3}.

– István Zachar

Jun 29 ’12 at 19:41

@TysonWilliams Does it satisfy your needs ? Otherwise, could you give an appropriate example ?

– Artes

Jun 29 ’12 at 21:18

@IstvánZachar Thanks for reporting the problem. I updated the answer. If you see another problems, let me know about them. Nethertheless, I hope it is a good alternative to ruebenko’s answer, which is not too general, either .

– Artes

Jun 29 ’12 at 21:21

@Artes: Nice use of SameTest!

– István Zachar

Jun 29 ’12 at 21:39