-
Notifications
You must be signed in to change notification settings - Fork 0
/
stack.py
72 lines (52 loc) · 1.43 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
class Stack(object):
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def pop(self):
return self.items.pop()
def push(self, item):
self.items.append(item)
def size(self):
return len(self.items)
def peek(self):
return self.items[-1]
def par_checker(symbol_string):
s = Stack()
balanced = True
index = 0
while index < len(symbol_string) and balanced:
symbol = symbol_string[index]
if symbol in '([{':
s.push(symbol)
else:
if s.is_empty():
balanced = False
else:
top = s.pop()
if not matches(top, symbol):
balanced = False
index = index + 1
if balanced and s.is_empty():
return True
else:
return False
def matches(open, close):
openers = '([{'
closers = ')]}'
return openers.index(open) == closers.index(close)
print(par_checker('{{([][])}()}'))
print(par_checker('[{()]'))
def base_converter(dec_num, base):
digits = "0123456789ABCDEF"
stack = Stack()
while dec_num > 0:
rem = dec_num % base
stack.push(rem)
dec_num = dec_num // base
binary_string = ""
while not stack.is_empty():
binary_string += digits[stack.pop()]
return binary_string
print(base_converter(25, 2))
print(base_converter(26, 26))