Find index of closing bracket for a given opening bracket in an expression | Python program to find index of closing bracket for a given opening bracket . ; Function to find index of closing bracket for given opening bracket . ; If input is invalid . ; Create a deque to use it as a stack . ; Traverse through all elements starting from i . ; Push all starting brackets ; Pop a starting bracket for every closing bracket ; If deque becomes empty ; test function ; Driver code to test above method . ; should be 8 ; should be 7 ; should be 12 ; No matching bracket ; execution
from collections import deque NEW_LINE def getIndex ( s , i ) : NEW_LINE INDENT if s [ i ] != ' [ ' : NEW_LINE INDENT return - 1 NEW_LINE DEDENT d = deque ( ) NEW_LINE for k in range ( i , len ( s ) ) : NEW_LINE INDENT if s [ k ] == ' [ ' : NEW_LINE INDENT d . append ( s [ i ] ) NEW_LINE DEDENT elif s [ k ] == ' ] ' : NEW_LINE INDENT d . popleft ( ) NEW_LINE DEDENT if not d : NEW_LINE INDENT return k NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT def test ( s , i ) : NEW_LINE INDENT matching_index = getIndex ( s , i ) NEW_LINE print ( s + " , ▁ " + str ( i ) + " : ▁ " + str ( matching_index ) ) NEW_LINE DEDENT def main ( ) : NEW_LINE INDENT test ( " [ ABC [ 23 ] ] [89 ] " , 0 ) NEW_LINE test ( " [ ABC [ 23 ] ] [89 ] " , 4 ) NEW_LINE test ( " [ ABC [ 23 ] ] [89 ] " , 9 ) NEW_LINE test ( " [ ABC [ 23 ] ] [89 ] " , 1 ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT main ( ) NEW_LINE DEDENT