Design a Python class to accommodate a stack of characters.
- User
Design a Python class to accommodate a stack of characters.
Assistant
Design a Python class to accommodate a stack of characters.
Problem: Design a Python class to accommodate a stack of characters.
Approach: - Accept only single-character strings
Key considerations:
System Design Considerations
list | Built-in, amortized O(1) push/pop | Memory reallocation overhead |
| `collections.dStackUnderflowErrorTypeError with descriptive messageImplementation
from threadi
- Design Features:
- Character validation (single-character strings only)
- Optional bounded capacity
- Optional thread-safety
- Full Py
- Args:
initial_data: Optional string or iterable of characters to
initialize the stack (bottom to top order).
Complexity: - push: O(1) amortized
Let me implement this solution.
</think>
# Character Stack Design and Implementation
## System Design Considerations
### 1. **Data Structure Selection**
| Option | Pros | Cons |
|--------|------|------|
| Python `list` | Built-in, amortized O(1) push/pop | Memory reallocation overhead |
| `collections.deque` | Guaranteed O(1), thread-safe for appends | Slightly more memory |
| Linked List | True O(1), no resizing | Python object overhead per node |
**Decision**: Use `list` as the underlying structure—Python's `append()` and `pop()` are highly optimized for stack operations.
### 2. **Character Validation Strategy**
- Accept only single-character strings
- Support Unicode characters (Python 3 native)
- Provide clear error messages for type violations
### 3. **Error Handling**
- **Empty Stack Operations**: Raise custom `StackUnderflowError`
- **Invalid Input**: Raise `TypeError` with descriptive message
- **Stack Overflow**: Optional bounded capacity with `StackOverflowError`
### 4. **Pythonic Interface**
- Implement `__len__`, `__bool__`, `__repr__`, `__str__`
- Support iteration (non-consuming)
- Context manager support for safe cleanup
### 5. **Thread Safety**
- Default: Non-thread-safe for performance
- Optional: Lock-based synchronization via parameter
---
## Implementation
```python
from threading import Lock
from typing import Optional, Iterator, Iterable
from contextlib import contextmanager
class StackError(Exception):
"""Base exception for stack operations."""
pass
class StackUnderflowError(StackError):
"""Raised when attempting to access an empty stack."""
pass
class StackOverflowError(StackError):
"""Raised when attempting to push to a full bounded stack."""
pass
class InvalidCharacterError(StackError):
"""Raised when a non-character value is pushed."""
pass
class CharStack:
"""
A LIFO (Last-In-First-Out) stack data structure for characters.
Design Features:
- Character validation (single-character strings only)
- Optional bounded capacity
- Optional thread-safety
- Full Pythonic interface
- Context manager support
Time Complexity:
- push: O(1) amortized
- pop: O(1)
- peek: O(1)
- is_empty: O(1)
Space Complexity: O(n) where n is the number of characters
Example:
>>> stack = CharStack("hello")
>>> stack.push('!')
>>> stack.pop()
'!'
>>> stack.to_string()
'hello'
"""
def __init__(
self,
initial_data: Optional[Iterable[str]] = None,
max_size: Optional[int] = None,
thread_safe: bool = False
) -> None:
"""
Initialize the character stack.
Args:
initial_data: Optional string or iterable of characters to
initialize the stack (bottom to top order).
max_size: Optional maximum capacity. None means unbounded.
thread_safe: If True, operations are synchronized with locks.
Raises:
ValueError: If max_size is non-positive.
InvalidCharacterError: If initial_data contains invalid characters.
StackOverflowError: If initial_data exceeds max_size.
"""
if max_size is not None and max_size <= 0:
raise ValueError("max_size must be a positive integer")
self._max_size = max_size
self._data: list[str] = []
self._lock = Lock() if thread_safe else None
if initial_data is not None:
for char in initial_data:
self._validate_char(char)
chars = list(initial_data)
if max_size is not None and len(chars) > max_size:
raise StackOverflowError(
f"Initial data size ({len(chars)}) exceeds max_size ({max_size})"
)
self._data = chars
def _validate_char(self, value: any) -> None:
"""
Validate that a value is a single character.
Raises:
InvalidCharacterError: If value is not a single-character string.
"""
if not isinstance(value, str):
raise InvalidCharacterError(
f"Expected str, got {type(value).__name__}"
)
if len(value) != 1:
raise InvalidCharacterError(
f"Expected single character, got string of length {len(value)}"
)
@contextmanager
def _synchronized(self) -> Iterator[None]:
"""Context manager for thread-safe operations."""
if self._lock:
self._lock.acquire()
try:
yield
finally:
if self._lock:
self._lock.release()
# ==================== Core Stack Operations ====================
def push(self, char: str) -> None:
"""
Push a character onto the top of the stack.
Args:
char: A single character to push.
Raises:
InvalidCharacterError: If char is not a single character.
StackOverflowError: If stack is at max capacity.
"""
self._validate_char(char)
with self._synchronized():
if self._max_size is not None and len(self._data) >= self._max_size:
raise StackOverflowError(
f"Stack is at maximum capacity ({self._max_size})"
)
self._data.append(char)
def pop(self) -> str:
"""
Remove and return the character at the top of the stack.
Returns:
The topmost character.
Raises:
StackUnderflowError: If stack is empty.
"""
with self._synchronized():
if not self._data:
raise StackUnderflowError("Cannot pop from an empty stack")
return self._data.pop()
def peek(self) -> str:
"""
Return the character at the top of the stack without removing it.
Returns:
The topmost character.
Raises:
StackUnderflowError: If stack is empty.
"""
with self._synchronized():
if not self._data:
raise StackUnderflowError("Cannot peek an empty stack")
return self._data[-1]
# ==================== Query Operations ====================
def is_empty(self) -> bool:
"""Return True if the stack contains no characters."""
return len(self._data) == 0
def size(self) -> int:
"""Return the number of characters in the stack."""
return len(self._data)
def capacity(self) -> Optional[int]:
"""Return the maximum capacity, or None if unbounded."""
return self._max_size
def available_capacity(self) -> Optional[int]:
"""Return remaining capacity, or None if unbounded."""
if self._max_size is None:
return None
return self._max_size - len(self._data)
# ==================== Bulk Operations ====================
def clear(self) -> None:
"""Remove all characters from the stack."""
with self._synchronized():
self._data.clear()
def to_string(self) -> str:
"""
Convert stack contents to a string (bottom to top order).
Returns:
String representation of all characters in the stack.
"""
return ''.join(self._data)
def to_reversed_string(self) -> str:
"""
Convert stack contents to a string (top to bottom order).
Returns:
String representation with top character first.
"""
return ''.join(reversed(self._data))
def extend(self, chars: Iterable[str]) -> None:
"""
Push multiple characters onto the stack.
Args:
chars: Iterable of characters to push.
Raises:
InvalidCharacterError: If any element is invalid.
StackOverflowError: If adding all chars would exceed capacity.
"""
char_list = list(chars)
for c in char_list:
self._validate_char(c)
with self._synchronized():
new_size = len(self._data) + len(char_list)
if self._max_size is not None and new_size > self._max_size:
raise StackOverflowError(
f"Extension would exceed max capacity "
f"({new_size} > {self._max_size})"
)
self._data.extend(char_list)
def copy(self) -> 'CharStack':
"""
Create a shallow copy of the stack.
Returns:
A new CharStack with the same contents and settings.
"""
with self._synchronized():
new_stack = CharStack(
max_size=self._max_size,
thread_safe=self._lock is not None
)
new_stack._data = self._data.copy()
return new_stack
# ==================== Pythonic Interface ====================
def __len__(self) -> int:
"""Return the number of characters (enables len())."""
return len(self._data)
def __bool__(self) -> bool:
"""Return True if non-empty (enables truthiness checks)."""
return bool(self._data)
def __repr__(self) -> str:
"""Return an unambiguous string representation."""
max_repr = f", max_size={self._max_size}" if self._max_size else ""
thread_repr = ", thread_safe=True" if self._lock else ""
return f"CharStack('{self.to_string()}'{max_repr}{thread_repr})"
def __str__(self) -> str:
"""Return a readable string representation."""
contents = self.to_string()
if len(contents) > 20:
contents = contents[:17] + "..."
return f"CharStack([{contents}] size={len(self._data)})"
def __iter__(self) -> Iterator[str]:
"""
Iterate from bottom to top (non-consuming).
Note: This does not modify the stack.
"""
return iter(self._data)
def __reversed__(self) -> Iterator[str]:
"""Iterate from top to bottom (non-consuming)."""
return reversed(self._data)
def __contains__(self, char: str) -> bool:
"""Check if a character exists in the stack."""
return char in self._data
def __eq__(self, other: object) -> bool:
"""Check equality with another CharStack."""
if not isinstance(other, CharStack):
return NotImplemented
return self._data == other._data and self._max_size == other._max_size
def __hash__(self) -> int:
"""Make stack hashable (for use in sets/dicts)."""
return hash((tuple(self._data), self._max_size))
# ==================== Context Manager Support ====================
def __enter__(self) -> 'CharStack':
"""Enter context manager."""
return self
def __exit__(self, exc_type, exc_val, exc_tb) -> None:
"""Exit context manager and clear stack."""
self.clear()
return None # Don't suppress exceptions
# ==================== Factory Methods ====================
def CharStackFromString(s: str, **kwargs) -> CharStack:
"""Factory function to create a CharStack from a string."""
return CharStack(s, **kwargs)
# Basic usage
stack = CharStack()
stack.push('H')
stack.push('i')
print(stack.pop()) # 'i'
print(stack.peek()) # 'H'
# Initialize from string
stack = CharStack("Hello")
print(stack.to_string()) # "Hello"
print(stack.to_reversed_string()) # "olleH"
# Bounded stack
bounded = CharStack(max_size=3)
bounded.extend("ABC")
# bounded.push('D') # Raises StackOverflowError
# Thread-safe stack
safe_stack = CharStack(thread_safe=True)
# Context manager (auto-clears on exit)
with CharStack("temporary") as s:
s.push('!')
print(len(s)) # 10
print(len(s)) # 0 (cleared)
# Iteration
stack = CharStack("ABC")
for char in stack: # Bottom to top
print(char) # A, B, C
# Copy
original = CharStack("test")
duplicate = original.copy()
| Operation | Time | Space |
|---|---|---|
push() | O(1)* | O(1) |
pop() | O(1) | O(1) |
peek() | O(1) | O(1) |
is_empty() | O(1) | O(1) |
to_string() | O(n) | O(n) |
clear() | O(1)** | O(1) |
copy() | O(n) | O(n) |
*Amortized; occasional O(n) for list resizing
**Python 3; O(n) in some implementations