Stack
code: python
from typing import List, Any
class Stack:
def __init__(self) -> None:
# O(1), O(1)
def push(self, item: Any) -> None:
self.items.append(item)
# O(1), O(n)
def pop(self) -> Any:
if self.is_empty():
raise IndexError("Stack is empty")
self.items = self.items:1 return item
# O(1), O(1)
def peek(self) -> Any:
if not self.is_empty():
raise IndexError("Stack is empty")
# O(1), O(1)
def is_empty(self) -> bool:
return len(self.items) == 0
# O(1), O(1)
def size(self) -> int:
return len(self.items)
import pytest
def test_stack_push_and_pop():
stack = Stack()
stack.push(1)
stack.push(2)
stack.push(3)
assert stack.pop() == 3
assert stack.pop() == 2
assert stack.pop() == 1
assert stack.is_empty()
def test_stack_peek():
stack = Stack()
stack.push(1)
stack.push(2)
assert stack.peek() == 2
assert stack.size() == 2
def test_stack_is_empty():
stack = Stack()
assert stack.is_empty()
stack.push(1)
assert not stack.is_empty()
def test_stack_size():
stack = Stack()
assert stack.size() == 0
stack.push(1)
stack.push(2)
assert stack.size() == 2
stack.pop()
assert stack.size() == 1
def test_pop_empty_stack():
stack = Stack()
with pytest.raises(IndexError):
stack.pop()
def test_peek_empty_stack():
stack = Stack()
with pytest.raises(IndexError):
stack.peek()
def test_stack_with_mixed_types():
stack = Stack()
stack.push(1)
stack.push("Hello")
assert stack.peek() == "Hello"
assert stack.size() == 2