       Re: finding the position of a pattern in list

• To: mathgroup at smc.vnet.net
• Subject: [mg64616] Re: finding the position of a pattern in list
• From: Jean-Marc Gulliet <jeanmarc.gulliet at gmail.com>
• Date: Fri, 24 Feb 2006 00:18:11 -0500 (EST)
• Organization: The Open University, Milton Keynes, UK
• References: <dtjjcv\$de7\$1@smc.vnet.net>
• Sender: owner-wri-mathgroup at wolfram.com

```Gang Ma wrote:
> Hi,
> I am working on a program to do the following: My data is a list of 0
> and 1. For example, {0,0,1,1,1,0,0,1,1,1,0}. I want to find the
> positions of all the pattern of {0,1}.  In my previous example, the
> first {0,1} is at 2 and and the second {0,1} appears at 7. I can
> write a loop to do this, but I have several thousands such lists,
> the computation will be time consuming using loop.
>
> My question is whether it is possible to use the pattern match to do
> this quickly.  If not for the list, do I need to convert the list to
> string then use some pattern match for string?  Thank you very much.
>
> regards,
>
> Gang Ma
>
>
>
Hi,

You could try the following one-liner see {In):

In:=
data={0,0,1,1,1,0,0,1,1,1,0};

In:=
Flatten[Position[Partition[data,2,1],{0,1}]]

Out=
{2,7}

How does it work?

In:=
data={0,0,1,1,1,0,0,1,1,1,0}

Out=
{0,0,1,1,1,0,0,1,1,1,0}

In:=
Partition[data,2]

Out=
{{0,0},{1,1},{1,0},{0,1},{1,1}}

Not what we are looking for: we want an offset of only one position.

In:=
Partition[data,2,1]

Out=
{{0,0},{0,1},{1,1},{1,1},{1,0},{0,0},{0,1},{1,1},{1,1},{1,0}}

In:=
Position[Partition[data,2,1],{0,1}]

Out=
{{2},{7}}

In:=
Flatten[Position[Partition[data,2,1],{0,1}]]

Out=
{2,7}

Performances seem quite good (Pentium IV, 512 MB, WinXP, Mathematica 5.2)

In:=
data=Table[Random[Integer],{10^6}];
Timing[Position[Partition[data,2,1],{0,1}];][]

Out=
1.204 Second

Best regards,
/J.M.

```

• Prev by Date: Re: Re: How if I want to assume that -------
• Next by Date: Re: finding the position of a pattern in list
• Previous by thread: Re: Re: finding the position of a pattern in list
• Next by thread: Re: finding the position of a pattern in list