File tree 1 file changed +45
-0
lines changed 1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Stack ():
2
+ def __init__ (self ):
3
+ self .items = []
4
+
5
+ def push (self ,item ):
6
+ self .items .append (item )
7
+
8
+ def pop (self ):
9
+ if not self .items :
10
+ return None
11
+ return self .items .pop ()
12
+
13
+ def peek (self ):
14
+ if self .items is None :
15
+ return None
16
+ return self .items [- 1 ]
17
+
18
+ def isEmpty (self ):
19
+ return self .items == []
20
+
21
+
22
+ def isBalanced (expression ):
23
+ s = Stack ()
24
+ balanced = True
25
+ index = 0
26
+ while index < len (expression ) and balanced :
27
+ symbol = expression [index ]
28
+ if symbol in '({[' :
29
+ s .push (symbol )
30
+ else :
31
+ top = s .pop ()
32
+ if not matches (top ,symbol ):
33
+ balanced = False
34
+ index += 1
35
+ if balanced and s .isEmpty ():
36
+ return True
37
+ else :
38
+ return False
39
+
40
+ def matches (open ,close ):
41
+ opens = '[{('
42
+ closers = ']})'
43
+ return opens .index (open ) == closers .index (close )
44
+
45
+ print isBalanced ('{([])}' )
You can’t perform that action at this time.
0 commit comments