Home > other >  [] python data structure of the stack application: matching brackets
[] python data structure of the stack application: matching brackets

Time:11-30

This procedure is MOOC Chen teacher of Beijing university courses, to improve the writing, welcome to communication, continuous learning progress
 
"'
Parentheses matching algorithm:
1. The input expression brackets
2. If left parenthesis stack
3. If there are any right parenthesis, but there is no left parenthesis matching (the stack is empty), return False
4. If you meet the right bracket and the stack is not empty, the stack right parenthesis must be compatible with the left parenthesis, if not match, returns False
5. If there are any other characters, it shall not do
6. When the expression character cycle end bracket, the stack is empty, parenthesis matching; Stack is not empty, the bracket does not match the
"'
The from Teststack import Stack

Def bracMatch (bracketItem) :
BracketList=list (bracketItem)
BraStack=Stack ()
Leftbrac="{[("
Rightbrac="}) "
Result=True
For the item in bracketList:
If the item in leftbrac:
BraStack. Push (item)
Elif item in rightbrac:
If braStack. IsEmpty () :
Result=False
The else:
If matchBoth (braStack. Peek (), the item) :
BraStack. Pop ()
The else:
Result=False

If braStack. IsEmpty () and the result:
Result=True
The else:
Result=False
Return the result

Def matchBoth (item1, item2) :
Leftbrac="{[("
Rightbrac="}) "
Return leftbrac. Index (item1)==rightbrac. Index (item2)

If __name__=="__main__" :
STR=input (" please enter the expression ")
If bracMatch (STR) :
Print (" matching brackets ")
The else:
Print (" does not match the brackets ")
  • Related