You have a bug
If the last value is a 1, and it is the end of the longest consecutive sequence, it won't be taken into account.
The fix is to change the return statement to this:
return max(size, len(one_list))
Unnecessary condition
If you know your input only contains 0 and 1 values,
then you can simplify this condition:
if num == 1:
# ...
elif num == 0 and size < len(one_list):
# ...
By dropping the num == 0
:
if num == 1:
# ...
elif size < len(one_list):
# ...
But note that this is not good enough, as there's still a bug hiding there as @veedrac explains in his answer, instead of an elif
, this should be rewritten using an else
.
Improving storage efficiency
There's no need to store the 1s as you count them.
You can just keep the count in a variable.
Testing
Instead of running your function using test data,
give a try to doctests, like this:
def consecutive_one(data):
"""
>>> consecutive_one([0, 1, 0, 1, 1, 0])
2
>>> consecutive_one([0, 1, 0, 1, 1, 1])
3
>>> consecutive_one([0, 1] * 10)
1
"""
# ... the implementation ...
To run all doctests within a file, run python -m doctest yourfile.py
.
When all tests pass, there is no output.
When something fails you will get a detailed report.
This is an excellent way to test your implementation,
and also to document usage with examples and expected outputs.