Added doctests , type hints for other/nested_brackets.py (#10872)

* Added doctests , type hints

* Update nested_brackets.py

---------

Co-authored-by: Christian Clauss <cclauss@me.com>
This commit is contained in:
Bhavesh Mathur 2023-10-24 14:33:22 +05:30 committed by GitHub
parent 481aff7928
commit 17059b7ece
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -14,31 +14,60 @@ brackets and returns true if S is nested and false otherwise.
""" """
def is_balanced(s): def is_balanced(s: str) -> bool:
stack = [] """
open_brackets = set({"(", "[", "{"}) >>> is_balanced("")
closed_brackets = set({")", "]", "}"}) True
>>> is_balanced("()")
True
>>> is_balanced("[]")
True
>>> is_balanced("{}")
True
>>> is_balanced("()[]{}")
True
>>> is_balanced("(())")
True
>>> is_balanced("[[")
False
>>> is_balanced("([{}])")
True
>>> is_balanced("(()[)]")
False
>>> is_balanced("([)]")
False
>>> is_balanced("[[()]]")
True
>>> is_balanced("(()(()))")
True
>>> is_balanced("]")
False
>>> is_balanced("Life is a bowl of cherries.")
True
>>> is_balanced("Life is a bowl of che{}ies.")
True
>>> is_balanced("Life is a bowl of che}{ies.")
False
"""
open_to_closed = {"{": "}", "[": "]", "(": ")"} open_to_closed = {"{": "}", "[": "]", "(": ")"}
stack = []
for i in range(len(s)): for symbol in s:
if s[i] in open_brackets: if symbol in open_to_closed:
stack.append(s[i]) stack.append(symbol)
elif symbol in open_to_closed.values() and (
elif s[i] in closed_brackets and ( not stack or open_to_closed[stack.pop()] != symbol
len(stack) == 0 or (len(stack) > 0 and open_to_closed[stack.pop()] != s[i])
): ):
return False return False
return not stack # stack should be empty
return len(stack) == 0
def main(): def main():
s = input("Enter sequence of brackets: ") s = input("Enter sequence of brackets: ")
if is_balanced(s): print(f"'{s}' is {'' if is_balanced(s) else 'not '}balanced.")
print(s, "is balanced")
else:
print(s, "is not balanced")
if __name__ == "__main__": if __name__ == "__main__":
from doctest import testmod
testmod()
main() main()