-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchallenge_balanced_symbols_solution.py
53 lines (37 loc) · 1.13 KB
/
challenge_balanced_symbols_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
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 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('(([{}]])'))