-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstack.py
91 lines (75 loc) · 1.78 KB
/
stack.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
from collections import deque
#stack = deque()
'''
deque_methods = dir(stack)
for method in deque_methods:
print(method)
stack.append('isak')
stack.append('mirry')
stack.append('sam')
stack.append('glor')
print(stack.pop())
print(stack)
'''
#Code below has used the deque class to create methods similar to those of inbuilt deque
class Stack:
def __init__(self):
self.container = deque()
def push(self, element):
self.container.append(element)
def pop(self):
return self.container.pop()
def peek(self):
return self.container[-1]
def is_empty(self):
return len(self.container) == 0
def size(self):
return len(self.container)
def print_stack(self):
return self.container
stack = Stack()
stack.push(89)
stack.push(34)
stack.push('Isak')
stack.push('Shark')
stack.pop()
'''
try:
stack_elements = stack.print_stack()
print(stack_elements)
print(f'Empty?: {stack.is_empty()}')
print(f'Size: {stack.size()}')
print(f'peek element: {stack.peek()}')
except Exception as e:
print('Exception: ', e, '\nCannot Peek empty list')
'''
#reverse a string
def reverse_string(string):
stack = Stack()
for ch in string:
stack.push(ch)
rvstr = ''
while stack.size() != 0:
rvstr += stack.pop()
return rvstr
#print(reverse_string('We will conquer Covid-19'))
def is_match(ch1,ch2):
match_dict = {
')' : '(',
']' : '[',
'}' : '{'
}
return match_dict[ch1] == ch2
def check_bracket(bracket):
s = Stack()
for ch in bracket:
if ch == '(' or ch == '{' or ch == '[':
s.push(ch)
if ch == ')' or ch == '}' or ch ==']':
if s.size() == 0:
return False
if not is_match(ch,stack.pop()):
return False
return stack.size() == 0
brack_valid = check_bracket("({a+b})")
print(brack_valid)