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
Show file tree
Hide file tree
Changes from all commits
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
1 change: 1 addition & 0 deletions DIRECTORY.md
Original file line number Diff line number Diff line change
Expand Up @@ -520,6 +520,7 @@
* [Sierpinski Triangle](https://github.com/TheAlgorithms/Python/blob/master/other/sierpinski_triangle.py)
* [Tower Of Hanoi](https://github.com/TheAlgorithms/Python/blob/master/other/tower_of_hanoi.py)
* [Triplet Sum](https://github.com/TheAlgorithms/Python/blob/master/other/triplet_sum.py)
* [Two Pointer](https://github.com/TheAlgorithms/Python/blob/master/other/two_pointer.py)
* [Two Sum](https://github.com/TheAlgorithms/Python/blob/master/other/two_sum.py)
* [Word Patterns](https://github.com/TheAlgorithms/Python/blob/master/other/word_patterns.py)

Expand Down
38 changes: 26 additions & 12 deletions data_structures/stacks/balanced_parentheses.py
Original file line number Diff line number Diff line change
@@ -1,23 +1,37 @@
from .stack import Stack

__author__ = "Omkar Pathak"


def balanced_parentheses(parentheses):
""" Use a stack to check if a string of parentheses is balanced."""
stack = Stack(len(parentheses))
for parenthesis in parentheses:
if parenthesis == "(":
stack.push(parenthesis)
elif parenthesis == ")":
if stack.is_empty():
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
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please add a string that has no brackets and also an empty string.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done. Please review again.

>>> balanced_parentheses("1+2*3-4")
True
>>> balanced_parentheses("")
True
"""
stack = Stack()
bracket_pairs = {"(": ")", "[": "]", "{": "}"}
for bracket in parentheses:
if bracket in bracket_pairs:
stack.push(bracket)
elif bracket in (")", "]", "}"):
if stack.is_empty() or bracket_pairs[stack.pop()] != bracket:
return False
stack.pop()
return stack.is_empty()


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

testmod()

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