-
Notifications
You must be signed in to change notification settings - Fork 0
/
balancedParanthesisChecker.py
59 lines (48 loc) · 1.25 KB
/
balancedParanthesisChecker.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
56
57
58
59
__author__ = 'sarvps'
'''
Author: Sarv Parteek Singh
Course: CISC 610
Term: Late Summer
Final exam, Problem 3
Brief: Check whether paranthesis in an expression are balanced
'''
class Stack:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[len(self.items) - 1]
def size(self):
return len(self.items)
def paranthesisChecker(symbolList):
s = Stack()
balanced = True
index = 0
while index < len(symbolList) and balanced:
symbol = symbolList[index]
if symbol == '(':
s.push(symbol)
elif symbol == ')':
if s.isEmpty():
balanced = False
else:
top = s.pop()
if not matches(top, symbol):
balanced = False
index = index + 1
if balanced and s.isEmpty():
return True
else:
return False
def matches(open, close):
if open == '(' and close == ')':
return True
else:
return False
inputList = list('(())((())()')
print(paranthesisChecker(inputList))