Prefixes with more a than b | Function to count prefixes ; calculating for string S ; count == 0 or when N == 1 ; when all characters are a or a - b == 0 ; checking for saturation of string after repetitive addition ; Driver Code
def prefix ( k , n ) : NEW_LINE INDENT a = 0 NEW_LINE b = 0 NEW_LINE count = 0 NEW_LINE i = 0 NEW_LINE Len = len ( k ) NEW_LINE for i in range ( Len ) : NEW_LINE INDENT if ( k [ i ] == " a " ) : NEW_LINE INDENT a += 1 NEW_LINE DEDENT if ( k [ i ] == " b " ) : NEW_LINE INDENT b += 1 NEW_LINE DEDENT if ( a > b ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT if ( count == 0 or n == 1 ) : NEW_LINE INDENT print ( count ) NEW_LINE return 0 NEW_LINE DEDENT if ( count == Len or a - b == 0 ) : NEW_LINE INDENT print ( count * n ) NEW_LINE return 0 NEW_LINE DEDENT n2 = n - 1 NEW_LINE count2 = 0 NEW_LINE while ( n2 != 0 ) : NEW_LINE INDENT for i in range ( Len ) : NEW_LINE INDENT if ( k [ i ] == " a " ) : NEW_LINE INDENT a += 1 NEW_LINE DEDENT if ( k [ i ] == " b " ) : NEW_LINE INDENT b += 1 NEW_LINE DEDENT if ( a > b ) : NEW_LINE INDENT count2 += 1 NEW_LINE DEDENT DEDENT count += count2 NEW_LINE n2 -= 1 NEW_LINE if ( count2 == 0 ) : NEW_LINE INDENT break NEW_LINE DEDENT if ( count2 == Len ) : NEW_LINE INDENT count += ( n2 * count2 ) NEW_LINE break NEW_LINE DEDENT count2 = 0 NEW_LINE DEDENT return count NEW_LINE DEDENT S = " aba " NEW_LINE N = 2 NEW_LINE print ( prefix ( S , N ) ) NEW_LINE S = " baa " NEW_LINE N = 3 NEW_LINE print ( prefix ( S , N ) ) NEW_LINE