-4

I have a simple list where:

a = [1,1,1,0,0,1,0,1,1,0,1,1,1]

I am trying to find a way to determine when three ones appear adjacent to each other. So the output would say that there are two instances of this, based on the list above. The other posts I've read seem to use itertools.groupby(), but I'm not familiar with it so I was wondering if there is another way?

djl
  • 267
  • 1
  • 3
  • 13

2 Answers2

0

Here is one way, using itertools.groupby:

from itertools import groupby

a = [1, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 1, 1]    
adjacencies = [(item,  len(list(group))) for item,  group in groupby(a)]
ones = sum(item == 1 and length >= 3 for item,  length in adjacencies)
print ones

Here is another way, not using groupby:

a = [1, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 1, 1]
triplets = zip(a[0:], a[1:], a[2:])
ones = sum(set(t) == {1} for t in triplets)
print ones
Robᵩ
  • 163,533
  • 20
  • 239
  • 308
0

Here is one using itertools.groupby

import itertools

a = [1,1,1,0,0,1,0,1,1,0,1,1,1]

n=0
for x in itertools.groupby(a):
    c = 1
    for y in x[1]:
        c+=1
    if c==3:
        n+=1
Brian
  • 1,659
  • 12
  • 17