-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.py
More file actions
89 lines (64 loc) · 1.84 KB
/
stack.py
File metadata and controls
89 lines (64 loc) · 1.84 KB
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
"""
Stack implementation and related uses.
Run tests:
python3 -m unittest stack.py
"""
import unittest
class Stack:
def __init__(self):
self.items = list()
def is_empty(self):
return bool(self.items)
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[-1]
def size(self):
return len(self.items)
def is_balanced(string, opening='({[', closing=']})'):
"""
test if a string contains a balanced number of
opening and closing symbols
"""
stack = list()
for char in string:
if char in opening:
stack.append(opening)
elif char in closing:
if not stack:
# should not be empty at this point
return False
stack.pop()
else:
continue
if stack:
return False
else:
return True
class BalancedParenthesisTest(unittest.TestCase):
def _assert(self, bool_, strings):
if bool_:
assertion = getattr(self, 'assertTrue')
else:
assertion = getattr(self, 'assertFalse')
for string in strings:
got = is_balanced(string)
assertion(got, msg="Error for '{}'".format(string))
def test_basic_balanced(self):
strings = [
'()', '[]', '{}',
'(())', '[[]]', '{{}}',
'((()()))', '[[[][]]]', '{{{}{}}}',
'{{ ( ) [] () }}', '( [] {} () )',
'awef ( ) awef', '(awef) (awef)', '((awef) (awef)) ( awef)',
]
self._assert(True, strings)
def test_basic_imbalanced(self):
strings = [
'((', '()))', '(((())',
'[[[', '[[][]', '{{}', '}}}}}',
'{{ () [] }',
]
self._assert(False, strings)