2019-10-05 05:14:13 +00:00
|
|
|
"""
|
2016-12-11 09:23:33 +00:00
|
|
|
The nested brackets problem is a problem that determines if a sequence of
|
|
|
|
brackets are properly nested. A sequence of brackets s is considered properly nested
|
|
|
|
if any of the following conditions are true:
|
|
|
|
|
2019-11-16 07:05:00 +00:00
|
|
|
- s is empty
|
|
|
|
- s has the form (U) or [U] or {U} where U is a properly nested string
|
|
|
|
- s has the form VW where V and W are properly nested strings
|
2016-12-11 09:23:33 +00:00
|
|
|
|
|
|
|
For example, the string "()()[()]" is properly nested but "[(()]" is not.
|
|
|
|
|
2020-06-16 08:09:19 +00:00
|
|
|
The function called is_balanced takes as input a string S which is a sequence of
|
|
|
|
brackets and returns true if S is nested and false otherwise.
|
2019-10-05 05:14:13 +00:00
|
|
|
"""
|
|
|
|
|
|
|
|
|
2022-10-12 22:54:20 +00:00
|
|
|
def is_balanced(s):
|
2016-12-11 09:23:33 +00:00
|
|
|
|
|
|
|
stack = []
|
2019-10-05 05:14:13 +00:00
|
|
|
open_brackets = set({"(", "[", "{"})
|
|
|
|
closed_brackets = set({")", "]", "}"})
|
|
|
|
open_to_closed = dict({"{": "}", "[": "]", "(": ")"})
|
2017-10-20 16:35:53 +00:00
|
|
|
|
2022-10-12 22:54:20 +00:00
|
|
|
for i in range(len(s)):
|
2017-10-20 16:35:53 +00:00
|
|
|
|
2022-10-12 22:54:20 +00:00
|
|
|
if s[i] in open_brackets:
|
|
|
|
stack.append(s[i])
|
2017-10-20 16:35:53 +00:00
|
|
|
|
2022-10-12 22:54:20 +00:00
|
|
|
elif s[i] in closed_brackets:
|
2019-10-05 05:14:13 +00:00
|
|
|
if len(stack) == 0 or (
|
2022-10-12 22:54:20 +00:00
|
|
|
len(stack) > 0 and open_to_closed[stack.pop()] != s[i]
|
2019-10-05 05:14:13 +00:00
|
|
|
):
|
2016-12-11 09:23:33 +00:00
|
|
|
return False
|
2017-10-20 16:35:53 +00:00
|
|
|
|
|
|
|
return len(stack) == 0
|
2016-12-11 09:23:33 +00:00
|
|
|
|
|
|
|
|
|
|
|
def main():
|
2020-06-16 08:09:19 +00:00
|
|
|
s = input("Enter sequence of brackets: ")
|
|
|
|
if is_balanced(s):
|
|
|
|
print(s, "is balanced")
|
2016-12-11 09:23:33 +00:00
|
|
|
else:
|
2020-06-16 08:09:19 +00:00
|
|
|
print(s, "is not balanced")
|
2016-12-11 09:23:33 +00:00
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
main()
|