Re: Union - simple question
- To: mathgroup at smc.vnet.net
- Subject: [mg49046] Re: Union - simple question
- From: koopman at sfu.ca (Ray Koopman)
- Date: Tue, 29 Jun 2004 04:50:32 -0400 (EDT)
- References: <cbol4e$4e0$1@smc.vnet.net>
- Sender: owner-wri-mathgroup at wolfram.com
Steve Gray <stevebg at adelphia.net> wrote in message news:<cbol4e$4e0$1 at smc.vnet.net>... > I don't understand why Union here doesn't work. (Sort is ok.) > I want Union to eliminate list items where element [[1,2]] is > duplicated. In this case, the first and third are duplicated because > they both have '5' there. > > ts = {{{1,2,3},5}, {{3,8,7},6}, {{7,8,9},5}, {{1,2,3},7}}; > Sort [ts, #1[[2]] < #2[[2]] &] > Union[ts, Sametest -> (#1[[2]] == #2[[2]]&)] > > Any help will be appreciated. In[1]:= ts = {{{1,2,3},5},{{3,8,7},6},{{7,8,9},5},{{1,2,3},7}} Out[1]= {{{1,2,3},5},{{3,8,7},6},{{7,8,9},5},{{1,2,3},7}} In[2]:= Sort@ts Out[2]= {{{1,2,3},5},{{1,2,3},7},{{3,8,7},6},{{7,8,9},5}} In[3]:= Reverse@Sort@ts Out[3]= {{{7,8,9},5},{{3,8,7},6},{{1,2,3},7},{{1,2,3},5}} In[4]:= sametest = (Print@{##}; #1[[2]] == #2[[2]]) & Out[4]= (Print[{##1}];#1\[LeftDoubleBracket]2\[RightDoubleBracket]==#2 \[LeftDoubleBracket]2\[RightDoubleBracket])& In[5]:= Union[ts, SameTest->sametest] {{{1,2,3},7},{{1,2,3},5}} {{{3,8,7},6},{{1,2,3},7}} {{{7,8,9},5},{{3,8,7},6}} Out[5]= {{{1,2,3},5},{{1,2,3},7},{{3,8,7},6},{{7,8,9},5}} In[6]:= Union[Sort@ts, SameTest->sametest] {{{1,2,3},7},{{1,2,3},5}} {{{3,8,7},6},{{1,2,3},7}} {{{7,8,9},5},{{3,8,7},6}} Out[6]= {{{1,2,3},5},{{1,2,3},7},{{3,8,7},6},{{7,8,9},5}} In[7]:= Union[Reverse@Sort@ts, SameTest->sametest] {{{1,2,3},7},{{1,2,3},5}} {{{3,8,7},6},{{1,2,3},7}} {{{7,8,9},5},{{3,8,7},6}} Out[7]= {{{1,2,3},5},{{1,2,3},7},{{3,8,7},6},{{7,8,9},5}} It looks like Union first sorts the list, and then uses SameTest only to check adjacent elements (which it passes to SameTest in reverse order!).