-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstack_challenge_solution.py
57 lines (39 loc) · 1.19 KB
/
stack_challenge_solution.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
class Stack:
def __init__(self):
self.items = []
def push (self, item):
self.items.append(item)
def pop(self):
if self.items:
return self.items.pop()
return None
def is_empty(self):
return self.items == []
def match_symbols(symbol_str):
symbol_pairs = {
'(':')',
'[':']',
'{':'}',
}
openers = symbol_pairs.keys()
my_stack = Stack()
index = 0
while index < len(symbol_str):
symbol = symbol_str[index]
if symbol in openers:
my_stack.push(symbol)
else: # The symbol is a closer
# If the Stack is already empty, the symbols are not balanced
if my_stack.is_empty():
return False
# If there are still items in the Stack, check for a mis-match.
else:
top_item = my_stack.pop()
if symbol != symbol_pairs[top_item]:
return False
index += 1
if my_stack.is_empty():
return True
return False # Stack is not empty so symbols were not balanced
print(match_symbols('([{}])'))
print(match_symbols('(([{}]])]'))