/
stack_with_max.py
68 lines (50 loc) · 2.04 KB
/
stack_with_max.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
import collections
from typing import List
from test_framework import generic_test
from test_framework.test_failure import TestFailure
class Stack:
ElementWithCachedMax = collections.namedtuple('ElementWithCachedMax',
('element', 'max'))
def __init__(self) -> None:
self._element_with_cached_max: List[Stack.ElementWithCachedMax] = []
def empty(self) -> bool:
return len(self._element_with_cached_max) == 0
def max(self) -> int:
return self._element_with_cached_max[-1].max
def pop(self) -> int:
return self._element_with_cached_max.pop().element
def push(self, x: int) -> None:
self._element_with_cached_max.append(
self.ElementWithCachedMax(
x, x if self.empty() else max(x, self.max())))
def stack_tester(ops):
try:
s = Stack()
for (op, arg) in ops:
if op == 'Stack':
s = Stack()
elif op == 'push':
s.push(arg)
elif op == 'pop':
result = s.pop()
if result != arg:
raise TestFailure('Pop: expected ' + str(arg) + ', got ' +
str(result))
elif op == 'max':
result = s.max()
if result != arg:
raise TestFailure('Max: expected ' + str(arg) + ', got ' +
str(result))
elif op == 'empty':
result = int(s.empty())
if result != arg:
raise TestFailure('Empty: expected ' + str(arg) +
', got ' + str(result))
else:
raise RuntimeError('Unsupported stack operation: ' + op)
except IndexError:
raise TestFailure('Unexpected IndexError exception')
if __name__ == '__main__':
exit(
generic_test.generic_test_main('stack_with_max.py',
'stack_with_max.tsv', stack_tester))