-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathParentheses.py
More file actions
83 lines (60 loc) · 1.86 KB
/
Copy pathParentheses.py
File metadata and controls
83 lines (60 loc) · 1.86 KB
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
class Stack (object):
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 __str__ (self):
return str(self.items)
def parChecker (symbolString):
s = Stack()
balanced = True
index = 0
print("Testing string ",symbolString)
while index < len(symbolString) and balanced:
symbol = symbolString[index]
print("symbol:",symbol)
if symbol in "([{":
s.push (symbol)
print(" pushed: stack now ",str(s))
input("paused")
else:
# there had better be a matching open paren on the stack
if s.isEmpty():
balanced = False
print(" Stack is empty! Aborting")
input("paused")
else:
top = s.pop()
if not matches (top,symbol):
balanced = False
print(" Mismatch found! Aborting")
input("paused")
else:
print(" Match found: stack after pop now: ",str(s))
input("paused")
index += 1
# while loop is over
if balanced and s.isEmpty():
return True
else:
return False
def matches (open, close):
opens = "([{"
closes = ")]}"
return opens.index(open) == closes.index(close)
def main():
example1 = "()[()]"
print (example1,":"," matches\n\n" if parChecker(example1) else " does not match\n\n")
example2 = "([])({})"
print (example2,":"," matches\n\n" if parChecker(example2) else " does not match\n\n")
example3 = "{]()"
print (example3,":"," matches\n\n" if parChecker(example3) else " does not match\n\n")
main()