Reputation: 1319
I have an array of binary numbers in Python like this:
binary = [1,1,0,1,1,0,0]
So, I wanna have a method to return how many times is a sequence of binary number, for example:
binary = [1,1,0,1,1,0,0]
must return 4, because there are 1 sequence of 'twice 1', after there is a sequence of 'one 0', then there are a sequence of 'twice 1' and finally a sequence of 'twice 0'
other example:
binary = [1,0,0,1,1,1,1]
must return 3, because there is 1 sequence of 'one 1', after there are a sequence of 'twice 0', finally there are a sequence of 'four 1s.'
Thank you so much.
Upvotes: 0
Views: 87
Reputation: 87064
This is trivial with itertools.groupby()
:
from itertools import groupby
binary_lists = [[1,1,0,1,1,0,0],
[1,0,0,1,1,1,1],
'1111111111',
'1',
[0],
[1,0,1,0,1,0,1],
[],
'',
'aaccgta']
for bits in binary_lists:
print '{} : num sequences = {}'.format(bits, len(list(groupby(bits))))
Output:
[1, 1, 0, 1, 1, 0, 0] : num sequences = 4
[1, 0, 0, 1, 1, 1, 1] : num sequences = 3
1111111111 : num sequences = 1
1 : num sequences = 1
[0] : num sequences = 1
[1, 0, 1, 0, 1, 0, 1] : num sequences = 7
[] : num sequences = 0
: num sequences = 0
aaccgta : num sequences = 5
Upvotes: 4
Reputation: 348
Any ideas how to improve?
def countSeq(src):
last = src[0]
count = 0
current = 1
while current < len(src):
if src[current] != last:
count += 1
last = src[current]
current += 1
return count + 1 # last
Test:
>>> countSeq([1,1,0,1,1,0,0])
4
>>> countSeq([1,0,0,1,1,1,1])
3
Upvotes: 4