May 2017
Intermediate to advanced
310 pages
8h 5m
English
Now let us look at an example of how we can use our stack implementation. We are going to write a little function that will verify whether a statement containing brackets--(, [, or {--is balanced, that is, whether the number of closing brackets matches the number of opening brackets. It will also ensure that one pair of brackets really is contained in another:
def check_brackets(statement): stack = Stack() for ch in statement: if ch in ('{', '[', '('): stack.push(ch) if ch in ('}', ']', ')'): last = stack.pop() if last is '{' and ch is '}': continue elif last is '[' and ch is ']': continue elif last is '(' and ch is ')': continue else: return False if stack.size > 0: return False else: return ...Read now
Unlock full access