2019-07-31 15:14:35 +00:00
|
|
|
from .stack import Stack
|
2018-10-19 12:48:28 +00:00
|
|
|
|
2019-10-05 05:14:13 +00:00
|
|
|
__author__ = "Omkar Pathak"
|
2018-10-19 12:48:28 +00:00
|
|
|
|
|
|
|
|
|
|
|
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:
|
2019-10-05 05:14:13 +00:00
|
|
|
if parenthesis == "(":
|
2018-10-19 12:48:28 +00:00
|
|
|
stack.push(parenthesis)
|
2019-10-05 05:14:13 +00:00
|
|
|
elif parenthesis == ")":
|
2018-12-17 14:45:54 +00:00
|
|
|
if stack.is_empty():
|
|
|
|
return False
|
2018-10-19 12:48:28 +00:00
|
|
|
stack.pop()
|
2018-12-17 14:45:54 +00:00
|
|
|
return stack.is_empty()
|
2018-10-19 12:48:28 +00:00
|
|
|
|
|
|
|
|
2019-10-05 05:14:13 +00:00
|
|
|
if __name__ == "__main__":
|
|
|
|
examples = ["((()))", "((())", "(()))"]
|
|
|
|
print("Balanced parentheses demonstration:\n")
|
2018-10-19 12:48:28 +00:00
|
|
|
for example in examples:
|
2019-10-05 05:14:13 +00:00
|
|
|
print(example + ": " + str(balanced_parentheses(example)))
|