Skip to content

Balanced parentheses #3768

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Oct 29, 2020
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
eliminate is_paired
  • Loading branch information
realDuYuanChao committed Oct 28, 2020
commit 772471265f81cb0aeb220525efa6ab20596d98b7
25 changes: 4 additions & 21 deletions data_structures/stacks/balanced_parentheses.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,42 +12,25 @@ def balanced_parentheses(parentheses: str) -> bool:
>>>
"""
stack = Stack()
bracket_pairs = {"(": ")", "[": "]", "{": "}"}
for bracket in parentheses:
if bracket in ("(", "[", "{"):
stack.push(bracket)
elif bracket in (")", "]", "}"):
if stack.is_empty() or not is_paired(stack.pop(), bracket):
if stack.is_empty() or bracket_pairs[stack.pop()] != bracket:
return False
return stack.is_empty()


def is_paired(left_bracket: str, right_bracket: str) -> bool:
"""
>>> brackets = {"(" : ")", "[" : "]", "{" : "}"}
>>> for left_bracket, right_bracket in brackets.items():
... assert is_paired(left_bracket, right_bracket)
>>> is_paired("(", "}")
False
>>> is_paired("(", "]")
False
"""
return (
left_bracket == "(" and right_bracket == ")" or
left_bracket == "[" and right_bracket == "]" or
left_bracket == "{" and right_bracket == "}"
)


if __name__ == "__main__":
from doctest import testmod

testmod()

examples = ["((()))", "((())", "(()))"]
print("Balanced parentheses demonstration:\n")
for example in examples:
print(
example,
"is",
f"{example} is",
"balanced" if balanced_parentheses(example) else "not balanced",
)