Count number of tails since the last head

Viewed 334

Consider a sequence of coin tosses: 1, 0, 0, 1, 0, 1 where tail = 0 and head = 1.

The desired output is the sequence: 0, 1, 2, 0, 1, 0

Each element of the output sequence counts the number of tails since the last head.

I have tried a naive method:

def timer(seq):
    if seq[0] == 1: time = [0]
    if seq[0] == 0: time = [1]
    for x in seq[1:]:
        if x == 0: time.append(time[-1] + 1)
        if x == 1: time.append(0)
    return time

Question: Is there a better method?

6 Answers
Related