Count possible binary strings of length N without P consecutive 0 s and Q consecutive 1 s | Function to check if a satisfy the given condition or not ; Stores the length of string ; Stores the previous character of the string ; Stores the count of consecutive equal characters ; Traverse the string ; If current character is equal to the previous character ; If count of consecutive 1 s is more than Q ; If count of consecutive 0 s is more than P ; Reset value of cnt ; If count of consecutive 1 s is more than Q ; If count of consecutive 0 s is more than P ; Function to count all distinct binary strings that satisfy the given condition ; Stores the length of str ; If length of str is N ; If str satisfy the given condition ; If str does not satisfy the given condition ; Append a character '0' at end of str ; Append a character '1' at end of str ; Return total count of binary strings ; Driver Code
def checkStr ( str , P , Q ) : NEW_LINE INDENT N = len ( str ) NEW_LINE prev = str [ 0 ] NEW_LINE cnt = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( str [ i ] == prev ) : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT else : NEW_LINE INDENT if ( prev == '1' and cnt >= Q ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( prev == '0' and cnt >= P ) : NEW_LINE INDENT return False NEW_LINE DEDENT cnt = 1 NEW_LINE DEDENT prev = str [ i ] NEW_LINE DEDENT if ( prev == '1' and cnt >= Q ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( prev == '0' and cnt >= P ) : NEW_LINE INDENT return False NEW_LINE DEDENT return True NEW_LINE DEDENT def cntBinStr ( str , N , P , Q ) : NEW_LINE INDENT lenn = len ( str ) NEW_LINE if ( lenn == N ) : NEW_LINE INDENT if ( checkStr ( str , P , Q ) ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT return 0 NEW_LINE DEDENT X = cntBinStr ( str + '0' , N , P , Q ) NEW_LINE Y = cntBinStr ( str + '1' , N , P , Q ) NEW_LINE return X + Y NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 5 NEW_LINE P = 2 NEW_LINE Q = 3 NEW_LINE print ( cntBinStr ( " " , N , P , Q ) ) NEW_LINE DEDENT