-
Notifications
You must be signed in to change notification settings - Fork 1
/
BalancedBraces.py
45 lines (37 loc) · 965 Bytes
/
BalancedBraces.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
class Stack():
def __init__(self):
self.items = []
def push(self,item):
self.items.append(item)
def pop(self):
if not self.items:
return None
return self.items.pop()
def peek(self):
if self.items is None:
return None
return self.items[-1]
def isEmpty(self):
return self.items == []
def isBalanced(expression):
s = Stack()
balanced = True
index = 0
while index < len(expression) and balanced:
symbol = expression[index]
if symbol in '({[':
s.push(symbol)
else:
top = s.pop()
if not matches(top,symbol):
balanced = False
index += 1
if balanced and s.isEmpty():
return True
else:
return False
def matches(open,close):
opens = '[{('
closers = ']})'
return opens.index(open) == closers.index(close)
print isBalanced('{([])}')