Stack application bracket matching problem (Python version)
Check if parentheses are closed
- Sequential scan is checked for characters in the body (one character)
- Skip extraneous characters in check (all non-bracket characters are not related to current processing)
- The opening parenthesis is encountered to press it into the stack
- The top element of the stack pops up when closing parentheses are encountered
- If the match succeeds then continue, and the match fails to check for failure to end
1 defcheck_parens (text):2 #parentheses Match Check function, text is checked body string3Parens ="(){}[]"4Open_parens ="({["5opposite = {")":"(","}":"{","]":"["}6 7 defparentheses (text):8 #parenthesis Generator, each call returns the next parenthesis in text and its position9I.text_len =0,len (text)Ten whileTrue: One whileI < Text_len andText[i] not inchparens: Ai + = 1 - ifI >=Text_len: - return the yieldText[i],i -i + = 1 - -st = Sstack ()#Create Stack St + - forPR, I parentheses (text):#iterate over parentheses and positions in text + ifprinchOpen_parens:#open brackets, press stack and continue A St.push (PR) at elifSt.pop ()! = OPPOSITE[PR]:#close parenthesis Exit if match fails - Print("unmatching is found at"I" for", PR) - returnFalse - Else:#the match succeeds and does nothing. -
Stack application bracket matching problem (Python version)