Re: List representation using element position
- To: mathgroup at smc.vnet.net
- Subject: [mg72515] Re: List representation using element position
- From: Jean-Marc Gulliet <jeanmarc.gulliet at gmail.com>
- Date: Wed, 3 Jan 2007 05:36:42 -0500 (EST)
- Organization: The Open University, Milton Keynes, UK
- References: <enfgem$ss1$1@smc.vnet.net>
Dr. Wolfgang Hintze wrote: > Hello group, > happy new year to all of you! > > This one was put up in a slightly different form by me in March 2006. > It is now more general and it is lossless with respect to information: > > Given a list of integers which may repeat, e.g. > > lstIn = {2,3,4,4,2,1,1,5,4} > > provide a list of the different values and their respective positions in > the original list. In the example, > > LstOut= { > {1,{6,7}}, > {2,{2,5}}, ------------^ Above, I am sure you meant {2,{1,5}} > {3,{2}}, > {4,{3,4,9}}, > {5,{8}} > } > > Who finds the shortest function doing this task in general? Here is my function: In[1]:= myfun[lst_] := ({#1, Flatten[Position[lst, #1]]} & ) /@ Union[lst] Below, we check that the list returned by myfun is matches the expected format. In[2]:= lstIn = {2, 3, 4, 4, 2, 1, 1, 5, 4}; In[3]:= LstOut = {{1, {6, 7}}, {2, {1, 5}}, {3, {2}}, {4, {3, 4, 9}}, {5, {8}}}; In[4]:= myfun[lstIn] Out[4]= {{1, {6, 7}}, {2, {1, 5}}, {3, {2}}, {4, {3, 4, 9}}, {5, {8}}} In[5]:= % == LstOut Out[5]= True That works fine! > My solution appears 15 lines below By the way, your solution works "correctly" only for a list of positive integers. (Otherwise, the elements of the original list are replace by their index number, index number starting from one.) Compare, fPos[{a,b,a,a,e,f,e,d}] --> {{1,{1,3,4}},{2,{2}},{3,{8}},{4,{5,7}},{5,{6}}} vs myfun[{a,b,a,a,e,f,e,d}] --> {{a,{1,3,4}},{b,{2}},{d,{8}},{e,{5,7}},{f,{6}}} and fPos[{-3,1,-1,0,0,2,2.1,2.1}] --> {{1,{1}},{2,{3}},{3,{4,5}},{4,{2}},{5,{6}},{6,{7,8}}} vs myfun[{-3,1,-1,0,0,2,2.1,2.1}] --> {{-3,{1}},{-1,{3}},{0,{4,5}},{1,{2}},{2,{6}},{2.1,{7,8}}} > Thanks. > > Best regards, > Wolfgang > 1 > > > > 5 > > > > > 10 > > > > > fPos[lstIn_] := Module[{f = Flatten /@ (Position[lstIn, #1] & ) /@ > Union[lstIn]}, ({#1, f[[#1]]} & ) /@ Range[Length[f]]] > > In[15]:= > fPos[lstIn] > > Out[15]= > {{1, {6, 7}}, {2, {1, 5}}, {3, {2}}, {4, {3, 4, 9}}, {5, {8}}} >