Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find out how many sequences of binary '1' are in list

Tags:

python

What I am trying to do is to find out how many sequences of '1' are in a list read from the user input. For example, if my list looks like: mylist = [0, 1, 1, 1, 1, 1, 0, 1, 0, 0, 1] , then I want to print '3', because I have 3 sequences of 1. So far I have tried to find the indexes of '0' and see if those indexes are consecutive(which means is a sequence of 1 between my 2 zero's, but with no success.

like image 463
Laurentiu Amzarescu Avatar asked Dec 17 '22 19:12

Laurentiu Amzarescu


2 Answers

You can use itertools.groupby in a generator expression for sum:

from itertools import groupby
sum(1 for k, _ in groupby(mylist) if k)

This returns: 3

like image 54
blhsing Avatar answered Jan 03 '23 10:01

blhsing


If you know your list is just going to be made up of ones and zeroes, then you can join everything together as a string, split the string on every occurrence of '0', and then count up all of the strings of 1s (which will be any part that's not empty).

>>> mylist = [0, 1, 1, 1, 1, 1, 0, 1, 0, 0, 1]
>>> chunks_o_ones = [i for i in ''.join([str(i) for i in mylist]).split('0') if len(i) > 0]
>>> print(len(chunks_o_ones))
3

You could alternatively take the string and use a regular expression to find the '1' blocks:

>>> import re
>>> p = re.compile('1+')
>>> print(len(p.findall(''.join([str(i) for i in mylist]))))
3
like image 36
Bill M. Avatar answered Jan 03 '23 09:01

Bill M.