Skip to content

Commit 02ea8d0

Browse files
Merge pull request #52 from alvin562/master
added nested brackets problem
2 parents 19d1050 + 1d765f9 commit 02ea8d0

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

Diff for: other/nested_brackets.py

+57
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
'''
2+
The nested brackets problem is a problem that determines if a sequence of
3+
brackets are properly nested. A sequence of brackets s is considered properly nested
4+
if any of the following conditions are true:
5+
6+
- s is empty
7+
- s has the form (U) or [U] or {U} where U is a properly nested string
8+
- s has the form VW where V and W are properly nested strings
9+
10+
For example, the string "()()[()]" is properly nested but "[(()]" is not.
11+
12+
The function called is_balanced takes as input a string S which is a sequence of brackets and
13+
returns true if S is nested and false otherwise.
14+
15+
'''
16+
17+
18+
def is_balanced(S):
19+
20+
stack = []
21+
22+
for i in range(len(S)):
23+
24+
if S[i] == '(' or S[i] == '{' or S[i] == '[':
25+
stack.append(S[i])
26+
27+
else:
28+
29+
if len(stack) > 0:
30+
31+
pair = stack.pop() + S[i]
32+
33+
if pair != '[]' and pair != '()' and pair != '{}':
34+
return False
35+
36+
else:
37+
return False
38+
39+
if len(stack) == 0:
40+
return True
41+
42+
return False
43+
44+
45+
def main():
46+
47+
S = input("Enter sequence of brackets: ")
48+
49+
if is_balanced(S):
50+
print(S, "is balanced")
51+
52+
else:
53+
print(S, "is not balanced")
54+
55+
56+
if __name__ == "__main__":
57+
main()

0 commit comments

Comments
 (0)