Search code examples
python-3.xprobabilityprobability-theory

Write a program that counts the number of occurrences of "11" in an input sequence of zeros and ones in PYTHON3


Suppose I enter a list like [0,0,1,1,1,0], the program should print 2. I wrote a simple program like this:

def count11(seq):
    n= len(seq)
    print (n)
    cnt=0
    #i=0;
    print(cnt) 
    #print(i) 
    for i in range (0,n):
        if(seq[i] and seq[i+1]==1):
            cnt+=1;
            #i+=1;
    return cnt    
          
print(count11([0, 0, 1, 1, 1, 0])) 

But this condition will not work at extremes. like if len(seq)=5 and at i=4 the loop will show an error. Can you please help me to solve this issue. Thanks in advance.


Solution

  • just fix some problem

    def count11(seq):
        n = len(seq)
        print(n)
        cnt = 0
        # i=0;
        print(cnt)
        # print(i) 
        for i in range(0, n - 1):
            if seq[i] == 1 and seq[i + 1] == 1:
                cnt += 1
                # i+=1;
        return cnt
    
    
    print(count11([0, 0, 1, 1, 1, 0]))