15 Apr Wednesday 17:00 Python Practice – 23.04.12.
Question:
Please use stack knowledge to solve the following question:
Balanced parentheses means that each opening symbol has a corresponding closing symbol and the pairs of parentheses are properly nested. Consider the following correctly balanced strings of parentheses:
(()()()()) (((()))) (()((())()))
Compare those with the following, which are not balanced:
((((((()) ())) (()()(()
Write an program that will read a string of parentheses from left to right and decide whether the symbols are balanced. A stack is the appropriate data structure for keeping the parentheses. We can let the stack do the following steps:
Starting with an empty stack, process the parenthesis strings from left to right.
-
- If a symbol is an opening parenthesis, push it on the stack.
- If, on the other hand, a symbol is a closing parenthesis, pop the stack.
- As long as it is possible to pop the stack to match every closing symbol, the parentheses remain balanced.
- If at any time there is no opening symbol on the stack to match a closing symbol, the string is not balanced properly.
- At the end of the string, when all symbols have been processed, the stack should be empty
we can create a function called bracketChecker(brackets)
Sorry, the comment form is closed at this time.