Re: Extracting information from lists

• To: mathgroup at smc.vnet.net
• Subject: [mg63357] Re: Extracting information from lists
• From: "Jean-Marc Gulliet" <jeanmarc.gulliet at gmail.com>
• Date: Sun, 25 Dec 2005 02:19:35 -0500 (EST)
• Organization: The Open University, Milton Keynes, U.K.
• References: <dojefh\$fmb\$1@smc.vnet.net>
• Sender: owner-wri-mathgroup at wolfram.com

```"Tony King" <mathstutoring at ntlworld.com> a écrit dans le message de news:
dojefh\$fmb\$1 at smc.vnet.net...
| Does anyone know of a function that will allow me to extract the positions
| of the first elements of runs of similar elements within a list. For
| example, suppose that
|
| list={7,9,1,6,8,1,1,6,5,1,1,1,8,7,6,1,1,1,1,7}
|
| I need a function that will return
|
| {3,6,10,16}
|
| corresponding to the runs {1},{1,1},{1,1,1},{1,1,1,1} within list
|
| Many thanks
|
| Tony
|

Hi Tony,

The following set of functions will do what you want:

In[1]:=
searchRuns[lst_List] := Module[{data = lst, flag = False}, (Flatten[#1, 2]
& )[
Rest[Reap[For[cnt = 1, cnt < Length[data], cnt++, If[data[[cnt]] ==
data[[cnt + 1]],
If[flag == False, Sow[{data[[cnt]], cnt}]; flag = True], flag =
False]]]]]]

In[2]:=
searchNoRuns[lst_List] := Module[{data = lst, flag = False},
(Flatten[#1, 2] & )[Rest[Reap[For[cnt = 1, cnt < Length[data], cnt++,
If[data[[cnt]] == data[[cnt + 1]],
flag = True, If[flag == False, Sow[{data[[cnt]], cnt}], flag =
False]]]]]]]

In[3]:=
findRuns[lst_List] := Module[{data = lst, ru, noru, st}, ru =
searchRuns[data]; noru = searchNoRuns[data];
st = Union[First[Transpose[ru]]]; Union[ru, Cases[noru,
{(x_)?(Intersection[{#1}, st] != {} & ), y_}]]]

In[4]:=
findRuns[{7, 9, 1, 6, 8, 1, 1, 6, 5, 1, 1, 1, 8, 7, 6, 1, 1, 1, 1,
7}][[All,2]]

Out[4]= {3, 6, 10, 16}

In[5]:=
data = {7, 9, Pi, {E, I}, {E, I}, 1, 6, 6, 6, 8, Pi, a, a, 1, 1, 6, c, 5,
"word", 1, 1, 1, 8, "word", "word",
7, 6, 1, 1, 1, 1, 7, 2.7`20., 2.7, 2.7, 3, 3};

In[6]:=
findRuns[data]

Out[6]=
{{1, 20}, {1, 28}, {2.7`20., 33}, {3, 36}, {6, 7}, {6, 27}, {"word", 19},
{"word", 24}, {a, 12}, {{E, I}, 4}}

Best regards,
/J.M.

```

• Prev by Date: Re: Extracting information from lists
• Next by Date: Re: Questions regarding MatrixExp, and its usage
• Previous by thread: Re: Extracting information from lists
• Next by thread: Re: Extracting information from lists