Python/data_structures/stacks/balanced_parentheses.py
Christian Clauss 7b267e5e4f Fix data_structures to pass our Travis CI pytests (#1088)
* Fix data_structures to pass pytests

* Restore data_structures/stacks/__init__.py
2019-07-31 23:14:35 +08:00

27 lines
751 B
Python

from __future__ import print_function
from __future__ import absolute_import
from .stack import Stack
__author__ = 'Omkar Pathak'
def balanced_parentheses(parentheses):
""" Use a stack to check if a string of parentheses is balanced."""
stack = Stack(len(parentheses))
for parenthesis in parentheses:
if parenthesis == '(':
stack.push(parenthesis)
elif parenthesis == ')':
if stack.is_empty():
return False
stack.pop()
return stack.is_empty()
if __name__ == '__main__':
examples = ['((()))', '((())', '(()))']
print('Balanced parentheses demonstration:\n')
for example in examples:
print(example + ': ' + str(balanced_parentheses(example)))