Find occurrences of neighboring elements

Question:

Want to write a simple program that shoud count the number of occurrences of "11" in an input list of zeros and ones. The output should return a single number, which is the number of occurrences of "11".

I have implemented the following code:

def count_ones(seq):
   # return the number of occurrences as a number
   return sum(1 for i in seq if i != 0)

print(count_ones([0, 0, 1, 1, 1, 0])) # this should print 2

Now it doesn’t work as needed. How to improve the given code to get a proper output?

Asked By: ijdnam_alim

||

Answers:

Using zip

def count_ones(seq):
    # find pairs where current == next element == 1
    return sum(1 for x, y in zip(seq, seq[1:]) if x == y == 1)

Tests

print(count_ones([1, 0, 1])           # Output: 0
print(count_ones([1, 0, 1, 1])        # Output: 1
print(count_ones([0, 0, 1, 1, 1, 0])) # Output: 2
Answered By: DarrylG
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.