A poorly-made min stack

This commit is contained in:
Dan Buch 2023-10-21 07:18:56 -04:00
parent 345464d0d4
commit a3819c9b26
Signed by: meatballhat
GPG Key ID: A12F782281063434
2 changed files with 73 additions and 0 deletions

View File

@ -138,3 +138,27 @@ class Roman:
total += cls.ALL[c] total += cls.ALL[c]
return total return total
class MinStack:
def __init__(self):
self._v: list[int] = []
self._min: int | None = None
def push(self, val: int) -> None:
self._v.append(val)
if self._min is None or self._min > val:
self._min = val
def pop(self) -> None:
popped = self._v.pop(-1)
if popped == self._min:
self._min = min(self._v)
def top(self) -> int:
return self._v[-1]
def getMin(self) -> int: # no qa
return typing.cast(int, self._min)

View File

@ -28,3 +28,52 @@ def test_find_sqrt_ish(n: int, expected: int):
) )
def test_int_to_roman(n: int, expected: str): def test_int_to_roman(n: int, expected: str):
assert stuff.Roman.i2r(n) == expected assert stuff.Roman.i2r(n) == expected
@pytest.mark.parametrize(
("ops", "expected"),
[
(
(
[
("new",),
("push", -2),
("push", 0),
("push", -3),
("getMin",),
("pop",),
("top",),
("getMin",),
]
),
[
None,
None,
None,
None,
-3,
None,
0,
-2,
],
)
],
)
def test_min_stack(ops: list[tuple[str] | tuple[str, int]], expected: list[int | None]):
returned: list[int | None] = []
inst: stuff.MinStack | None = None
for op in ops:
if len(op) == 1:
if op[0] == "new":
inst = stuff.MinStack()
returned.append(None)
continue
returned.append(getattr(inst, op[0])())
continue
method, arg = op
returned.append(getattr(inst, method)(arg))
assert returned == expected