Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

Below, list is a representative sample of my list, which contains lists of integers. I would like to be able to input:

list = {{1, 2, 3}, {3, 2, 1}, {2, 1, 3}};
f[list]

and obtain the output:

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

In other words, {3, 2, 1} is considered to be the same as {1, 2, 3}, since in reverse it is exactly {1, 2, 3}. However, {2, 1, 3} is not considered to be the same as either {1, 2, 3} or {3, 2, 1}, because it does not match these lists in forward or in reverse.

What function f can I use to accomplish this?

I tried this:

DeleteDuplicates[list, MemberQ[list, #] || MemberQ[Reverse /@ list, #] &]

but it does not work, although I'm not sure why.

ADDENDUM

Now suppose I want to input:

list = {{1, 2, 3}, {3, 2, 1}, {2, 1, 3}, {1, 2, 3}};

and obtain:

list = {{1, 2, 3}, {2, 1, 3}};

where the "second" {1, 2, 3} is removed as a "normal" duplicate. How can I do this? I could do:

DeleteDuplicates[DeleteDuplicates[list, (#1 == Reverse[#2] &)]]

but is there an easier way?

share|improve this question
add comment

3 Answers 3

up vote 10 down vote accepted

This should do the job:

DeleteDuplicates[list, SameQ[#1, #2] || SameQ[#1, Reverse@#2] &]
share|improve this answer
    
This is what I want. For list = {{1, 2, 3}, {3, 2, 1}, {2, 1, 3}, {1, 2, 3}};, it gives {{1, 2, 3}, {2, 1, 3}}. Thanks. –  Andrew May 19 '12 at 19:39
add comment

You can use your condition directly

 DeleteDuplicates[list, (#1 == Reverse[#2] &)]

or use Union with SameTest

 Union[list, SameTest -> (#1 == Reverse[#2] &)]

Edit: For the new requirement, you need to Or the conditions for "sameness" (as in @acl's answer)

 DeleteDuplicates[list, (#1 == Reverse[#2] || #1 == #2 &)]
 Union[list, SameTest -> (#1 == Reverse[#2] || #1 == #2&)]
share|improve this answer
    
Okay, I think they both work now. Thanks. –  Andrew May 19 '12 at 19:30
1  
But now if list = {{1, 2, 3}, {3, 2, 1}, {2, 1, 3}, {1, 2, 3}} we get the duplicate element twice! –  acl May 19 '12 at 19:32
    
@acl: Right, this is not what I wanted to happen, but I failed to specify this requirement in my original post. Please see my edit above. –  Andrew May 19 '12 at 19:37
1  
@Andrew I think my answer does do this in a simple way –  acl May 19 '12 at 19:38
add comment

If your application allows for reversed elements to be interchangeable you can do this:

DeleteDuplicates[Sort[{#, Reverse@#}][[1]] & /@ list]

The advantage here is speed; this is perhaps two orders of magnitude faster on large sets than the methods already presented.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.