-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstack_exercises.py
66 lines (48 loc) · 1.21 KB
/
stack_exercises.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
60
61
62
63
64
65
66
from collections import deque
class Stack:
def __init__(self):
self.container = deque()
def push(self,value):
self.container.append(value)
def pop(self):
return self.container.pop()
def peek(self):
if self:
return self.container[-1]
def is_empty(self):
return len(self.container) == 0
def __len__(self):
return len(self.container)
# 1
def reverse_string(string):
stack = Stack()
for let in string:
stack.push(let)
t = ''
while not stack.is_empty():
t += stack.pop()
return t
print(reverse_string("We will conquere COVID-19"))
# 2
def is_balanced(string):
hashmap = {
'(' : ')',
'[' : ']',
'{' : '}'
}
stack = Stack()
for sym in string:
if sym in hashmap.keys():
stack.push(hashmap[sym])
if sym in hashmap.values():
if stack.peek() != sym:
return False
else:
stack.pop()
return True
print(is_balanced("({a+b})"))
print(is_balanced("))((a+b}{"))
print(is_balanced("((a+b))"))
print(is_balanced("))"))
print(is_balanced("[a+b]*(x+2y)*{gg+kk}"))
print(is_balanced("([)]"))