2019-07-31 15:14:35 +00:00
|
|
|
from .stack import Stack
|
2018-10-19 12:48:28 +00:00
|
|
|
|
|
|
|
|
2020-10-29 09:39:19 +00:00
|
|
|
def balanced_parentheses(parentheses: str) -> bool:
|
|
|
|
"""Use a stack to check if a string of parentheses is balanced.
|
|
|
|
>>> balanced_parentheses("([]{})")
|
|
|
|
True
|
|
|
|
>>> balanced_parentheses("[()]{}{[()()]()}")
|
|
|
|
True
|
|
|
|
>>> balanced_parentheses("[(])")
|
|
|
|
False
|
|
|
|
>>> balanced_parentheses("1+2*3-4")
|
|
|
|
True
|
|
|
|
>>> balanced_parentheses("")
|
|
|
|
True
|
|
|
|
"""
|
2021-10-26 18:33:08 +00:00
|
|
|
stack: Stack[str] = Stack()
|
2020-10-29 09:39:19 +00:00
|
|
|
bracket_pairs = {"(": ")", "[": "]", "{": "}"}
|
|
|
|
for bracket in parentheses:
|
|
|
|
if bracket in bracket_pairs:
|
|
|
|
stack.push(bracket)
|
2024-04-02 01:27:56 +00:00
|
|
|
elif bracket in (")", "]", "}") and (
|
|
|
|
stack.is_empty() or bracket_pairs[stack.pop()] != bracket
|
|
|
|
):
|
|
|
|
return False
|
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__":
|
2020-10-29 09:39:19 +00:00
|
|
|
from doctest import testmod
|
|
|
|
|
|
|
|
testmod()
|
|
|
|
|
2019-10-05 05:14:13 +00:00
|
|
|
examples = ["((()))", "((())", "(()))"]
|
|
|
|
print("Balanced parentheses demonstration:\n")
|
2018-10-19 12:48:28 +00:00
|
|
|
for example in examples:
|
2020-10-29 09:39:19 +00:00
|
|
|
not_str = "" if balanced_parentheses(example) else "not "
|
|
|
|
print(f"{example} is {not_str}balanced")
|