tprofiler.utils.stack
A high-performance stack implementation using deque.
This module provides a Stack class that implements the Last-In-First-Out (LIFO) data structure using Python’s deque for optimal performance. The stack supports all standard stack operations with O(1) time complexity.
Stack
- class tprofiler.utils.stack.Stack[source]
A high-performance stack implementation using deque.
This class implements a Last-In-First-Out (LIFO) data structure using Python’s deque for better performance compared to list-based implementations. All basic stack operations (push, pop, peek) have O(1) time complexity.
Example:
>>> stack = Stack() >>> stack.push(1) >>> stack.push(2) >>> stack.peek() 2 >>> stack.pop() 2 >>> stack.size 1
- __bool__()[source]
Support for boolean value judgment.
- Returns:
True if the stack is not empty, False if empty.
- Return type:
bool
Example:
>>> stack = Stack() >>> bool(stack) False >>> stack.push(1) >>> bool(stack) True
- __init__()[source]
Initialize an empty stack.
Uses deque implementation for better performance with O(1) operations.
- __len__()[source]
Support for the len() function.
- Returns:
The number of items in the stack.
- Return type:
int
Example:
>>> stack = Stack() >>> stack.push(1) >>> stack.push(2) >>> len(stack) 2
- __str__()[source]
Return a string representation of the stack.
- Returns:
String representation showing the stack contents.
- Return type:
str
Example:
>>> stack = Stack() >>> stack.push(1) >>> stack.push(2) >>> str(stack) 'Stack([1, 2])'
- clear()[source]
Remove all items from the stack.
After calling this method, the stack will be empty.
Example:
>>> stack = Stack() >>> stack.push(1) >>> stack.push(2) >>> stack.clear() >>> stack.is_empty True
- property is_empty
Check if the stack is empty.
- Returns:
True if the stack is empty, False otherwise.
- Return type:
bool
Time complexity: O(1)
Example:
>>> stack = Stack() >>> stack.is_empty True >>> stack.push(1) >>> stack.is_empty False
- peek()[source]
Return the top item from the stack without removing it.
- Returns:
The top item from the stack.
- Return type:
Any
- Raises:
IndexError – If the stack is empty.
Time complexity: O(1)
Example:
>>> stack = Stack() >>> stack.push(42) >>> stack.peek() 42 >>> stack.size 1
- pop()[source]
Remove and return the top item from the stack.
- Returns:
The top item from the stack.
- Return type:
Any
- Raises:
IndexError – If the stack is empty.
Time complexity: O(1)
Example:
>>> stack = Stack() >>> stack.push(42) >>> stack.pop() 42
- push(item)[source]
Push an item onto the top of the stack.
- Parameters:
item (Any) – The item to push onto the stack.
Time complexity: O(1)
Example:
>>> stack = Stack() >>> stack.push(42) >>> stack.size 1
- property size
Get the number of items in the stack.
- Returns:
The number of items in the stack.
- Return type:
int
Time complexity: O(1)
Example:
>>> stack = Stack() >>> stack.size 0 >>> stack.push(1) >>> stack.push(2) >>> stack.size 2