Distinct adjacent elements in a binary array | Python3 implementation of the above approach ; if array has only one element , return 1 ; For first element compare with only next element ; For remaining elements compare with both prev and next elements ; For last element compare with only prev element ; Driver code
def distinct ( arr ) : NEW_LINE INDENT count = 0 NEW_LINE if len ( arr ) == 1 : NEW_LINE INDENT return 1 NEW_LINE DEDENT for i in range ( 0 , len ( arr ) - 1 ) : NEW_LINE INDENT if ( i == 0 ) : NEW_LINE INDENT if ( arr [ i ] != arr [ i + 1 ] ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT elif ( i > 0 & i < len ( arr ) - 1 ) : NEW_LINE INDENT if ( arr [ i ] != arr [ i + 1 ] or arr [ i ] != arr [ i - 1 ] ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT DEDENT if ( arr [ len ( arr ) - 1 ] != arr [ len ( arr ) - 2 ] ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT return count NEW_LINE DEDENT arr = [ 0 , 0 , 0 , 0 , 0 , 1 , 0 ] NEW_LINE print ( distinct ( arr ) ) NEW_LINE