Python/data_structures/stacks/balanced_parentheses.py

26 lines
749 B
Python
Raw Normal View History

2018-10-19 12:48:28 +00:00
from __future__ import print_function
from __future__ import absolute_import
2018-12-17 14:44:38 +00:00
from stack import Stack
2018-10-19 12:48:28 +00:00
__author__ = 'Omkar Pathak'
def balanced_parentheses(parentheses):
2018-10-30 14:29:12 +00:00
""" Use a stack to check if a string of parentheses is balanced."""
2018-10-19 12:48:28 +00:00
stack = Stack(len(parentheses))
for parenthesis in parentheses:
if parenthesis == '(':
stack.push(parenthesis)
elif parenthesis == ')':
if stack.is_empty():
return False
2018-10-19 12:48:28 +00:00
stack.pop()
return stack.is_empty()
2018-10-19 12:48:28 +00:00
if __name__ == '__main__':
2018-12-17 14:45:16 +00:00
examples = ['((()))', '((())', '(()))']
2018-10-19 12:48:28 +00:00
print('Balanced parentheses demonstration:\n')
for example in examples:
print(example + ': ' + str(balanced_parentheses(example)))