forked from geekcomputers/Python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
balance_parenthesis.py
55 lines (43 loc) · 1.07 KB
/
balance_parenthesis.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
46
47
48
49
50
51
52
53
54
55
class Stack:
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def is_empty(self):
return self.items == []
def peek(self):
return self.items[-1]
def display(self):
return self.items
def is_same(p1, p2):
if p1 == "(" and p2 == ")":
return True
elif p1 == "[" and p2 == "]":
return True
elif p1 == "{" and p2 == "}":
return True
else:
return False
def is_balanced(check_string):
s = Stack()
index = 0
is_bal = True
while index < len(check_string) and is_bal:
paren = check_string[index]
if paren in "{[(":
s.push(paren)
else:
if s.is_empty():
is_bal = False
else:
top = s.pop()
if not is_same(top, paren):
is_bal = False
index += 1
if s.is_empty() and is_bal:
return True
else:
return False
print(is_balanced("[((())})]"))