File tree Expand file tree Collapse file tree 1 file changed +57
-0
lines changed Expand file tree Collapse file tree 1 file changed +57
-0
lines changed Original file line number Diff line number Diff line change 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 within quotes: " )
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 ()
You can’t perform that action at this time.
0 commit comments