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