Best strategy for finding a pattern in a sequence of integers

Slaunger Slaunger at gmail.com
Fri Nov 21 19:31:24 EST 2008


On 21 Nov., 18:10, Gerard flanagan <grflana... at gmail.com> wrote:
> Slaunger wrote:
> > Hi all,
>
> > I am a Python novice, and I have run into a problem in a project I am
> > working on, which boils down to identifying the patterns in a sequence
> > of integers, for example
>
> > .... 1 6 6 1 6 6 1 6 6 1 6 6 1 6 6 1 9 3 3 0 3 3 0 3 3 0 3 3 0 10 6 6
> > 1 6 6 1 6 6 1 6 6 1 6 6 1 6 6 1 6 6 1 9 3 3 0 3 3 0 3 3 0 3 3 0 10 6 6
> > 1 6 6 1 6 6 1 6 6 1 6 6 1 6 6 1 6 6 1 9 3 3 0 3 3 0 3 3 0 3 3 0 10 6 6
> > 1 6 6 1 6 6 1 6 6 1 6 6 1 6 6 1 6 6 1 9 3 3 0 3 3 0 3 3 0 3 3 0 10 6 6
> > 1 6 6 1 6 6 1 6 6 1 6 6 1 6 6 1 6 6 1 ...
>
> > I want to process this such that I get out two patterns, like:
> > (9, 3, 3, 0, 3, 3, 0, 3, 3, 0, 3, 3, 0)
> > and
> > (10, 6, 6, 1, 6, 6, 1, 6, 6, 1, 6, 6, 1, 6, 6, 1, 6, 6, 1, 6, 6, 1)
>
> Maybe:
>
> #-----------------------------------------------------------------
> data = '''
> 1 6 6 1 6 6 1 6 6 1 6 6 1 6 6 1 9 3 3 0 3 3 0 3 3 0 3 3 0 10 6 6
> 1 6 6 1 6 6 1 6 6 1 6 6 1 6 6 1 6 6 1 9 3 3 0 3 3 0 3 3 0 3 3 0 10 6 6
> 1 6 6 1 6 6 1 6 6 1 6 6 1 6 6 1 6 6 1 9 3 3 0 3 3 0 3 3 0 3 3 0 10 6 6
> 1 6 6 1 6 6 1 6 6 1 6 6 1 6 6 1 6 6 1 9 3 3 0 3 3 0 3 3 0 3 3 0 10 6 6
> 1 6 6 1 6 6 1 6 6 1 6 6 1 6 6 1 6 6 1'''
>
> data = [int(x) for x in data.split()]
>
> from itertools import groupby
>
> S1 = [0, 3, 9]
>
> s = set()
> for k, g in groupby(data, lambda x: x in S1):
>      seq = tuple(g)
>      # maybe the next line should be 'if 9 in seq or 10 in seq'?
>      if seq[0] in [9, 10]:
>          s.add(seq)
>
> print s
> #------------------------------------------------------------------
> set(
> [(9, 3, 3, 0, 3, 3, 0, 3, 3, 0, 3, 3, 0),
> (10, 6, 6, 1, 6, 6, 1, 6, 6, 1, 6, 6, 1, 6, 6, 1, 6, 6, 1, 6, 6, 1)])
>
> hth
>
> G.
Hi Gerard,
This definitely looks like a path to walk along, and I think your code
does the trick, although I have to play a little around with the
groupby method, of which I had no prior knowledge. I think I will
write some unit test cases to stress test you concept (on Monday, when
I am back at work). I appreciate your almost full implementation - it
would have sufficed to point me to the itertools module, and then I
think I would have figured out.
-- ~~~~



More information about the Python-list mailing list