Detecting sequences in lists

classic Classic list List threaded Threaded
3 messages Options
Reply | Threaded
Open this post in threaded view
|

Detecting sequences in lists

Tino Dai
Hi Everybody,

       Thank you so much for the information on sets. I think that that has certain uses, but in my case I can't find a way. I have been thinking about sequences in a list. Let me give you an example:

tset = [ 1,2,4,0,0,1,2,4,4]

What I want to do is detect the 1,2,4 sequence and perhaps how many.

What I have tried is
[1,2,4] in tset

and also

tset.count([1,2,4])

Is there a method or a function that does this in python, or am I left with DIY?

-Thanks,
Tino


_______________________________________________
Tutor maillist  -  [hidden email]
http://mail.python.org/mailman/listinfo/tutor
Reply | Threaded
Open this post in threaded view
|

Re: Detecting sequences in lists

Lutz Horn-4
Hi,

DIY is easy.

On Mon, 27 Aug 2007 09:20:53 -0400, "Tino Dai" <[hidden email]> said:
> What I want to do is detect the 1,2,4 sequence and perhaps how many.

>>> tset = [ 1,2,4,0,0,1,2,4,4]
>>> s = [1, 2, 4]
>>> c = 0
>>> for i in range(len(tset) - len(s)):
...     if tset[i:i+len(s)] == s:
...             c = c + 1
...             print "found at %d" % i
...
found at 0
found at 5
>>> print c
2

Regards
Lutz

--
<http://www.fastmail.fm/mail/?STKI=600622>

_______________________________________________
Tutor maillist  -  [hidden email]
http://mail.python.org/mailman/listinfo/tutor
Reply | Threaded
Open this post in threaded view
|

Re: Detecting sequences in lists

Kent Johnson
In reply to this post by Tino Dai
Tino Dai wrote:
> Hi Everybody,
>
>        Thank you so much for the information on sets. I think that that
> has certain uses, but in my case I can't find a way. I have been
> thinking about sequences in a list. Let me give you an example:
>
> tset = [ 1,2,4,0,0,1,2,4,4]
>
> What I want to do is detect the 1,2,4 sequence and perhaps how many.

There is nothing built-in for this. Here is a solution that uses index()
to quickly find potential starting points. It is based on this post to
c.l.py and the followup:
http://groups.google.com/group/comp.lang.python/msg/a03abee619ec54ef?hl=en&

This is likely to be much faster than Lutz' solution tset is long,
though you would have to test to be sure.

def subPositions(alist, innerlist):
     if innerlist == []:
             return
     first, start = innerlist[0], 0
     while 1:
         try:
                 p = alist.index(first, start)
         except ValueError:
                 return
         if alist[p: p + len(innerlist)] == innerlist:
                 yield p
         start = p+1

Kent
_______________________________________________
Tutor maillist  -  [hidden email]
http://mail.python.org/mailman/listinfo/tutor