patternpythonModerate
Count consecutive ones in a binary list
Viewed 0 times
binaryonescountlistconsecutive
Problem
There is a list consisting of zeroes and ones. I want to find out the length of the longest streak of ones. Is there a better solution?
def consecutive_one(data):
one_list = []
size = 0
for num in data:
if num == 1:
one_list.append(num)
elif num == 0 and size < len(one_list):
size = len(one_list)
one_list = []
return size
if __name__ == '__main__':
data = [0, 1, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0]
print(consecutive_one(data))Solution
Both your and janos' implementations are broken:
This is because you don't always reset after seeing a 0. Going from janos', you should have
and equivalent for the original.
You'll find that this functionality is largely provided by
data = [1, 0] * 10000
consecutive_one(data)
#>>> 140This is because you don't always reset after seeing a 0. Going from janos', you should have
longest = 0
current = 0
for num in data:
if num == 1:
current += 1
else:
longest = max(longest, current)
current = 0
return max(longest, current)and equivalent for the original.
You'll find that this functionality is largely provided by
itertools.groupby, though:from itertools import groupby
def len_iter(items):
return sum(1 for _ in items)
def consecutive_one(data):
return max(len_iter(run) for val, run in groupby(data) if val)Code Snippets
data = [1, 0] * 10000
consecutive_one(data)
#>>> 140longest = 0
current = 0
for num in data:
if num == 1:
current += 1
else:
longest = max(longest, current)
current = 0
return max(longest, current)from itertools import groupby
def len_iter(items):
return sum(1 for _ in items)
def consecutive_one(data):
return max(len_iter(run) for val, run in groupby(data) if val)Context
StackExchange Code Review Q#138550, answer score: 10
Revisions (0)
No revisions yet.