Number of flips to make binary string alternate | Set 1 | Utility method to flip a character ; Utility method to get minimum flips when alternate string starts with expected char ; if current character is not expected , increase flip count ; flip expected character each time ; method return minimum flip to make binary string alternate ; return minimum of following two 1 ) flips when alternate string starts with 0 2 ) flips when alternate string starts with 1 ; Driver code to test above method
def flip ( ch ) : NEW_LINE INDENT return '1' if ( ch == '0' ) else '0' NEW_LINE DEDENT def getFlipWithStartingCharcter ( str , expected ) : NEW_LINE INDENT flipCount = 0 NEW_LINE for i in range ( len ( str ) ) : NEW_LINE INDENT if ( str [ i ] != expected ) : NEW_LINE INDENT flipCount += 1 NEW_LINE DEDENT expected = flip ( expected ) NEW_LINE DEDENT return flipCount NEW_LINE DEDENT def minFlipToMakeStringAlternate ( str ) : NEW_LINE INDENT return min ( getFlipWithStartingCharcter ( str , '0' ) , getFlipWithStartingCharcter ( str , '1' ) ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT str = "0001010111" NEW_LINE print ( minFlipToMakeStringAlternate ( str ) ) NEW_LINE DEDENT