This quickstart guide will walk you through using the most common data structures in UCX DSA. All examples use real code directly from the source implementation.
# View the top element without removing ittop_element = stack.peek()print(top_element) # Output: 30# Pop the top elementpopped = stack.pop()print(popped) # Output: 30print(len(stack)) # Output: 2# Check if stack is emptyprint(stack.is_empty()) # Output: False
from dsa.stack import Stack# Fixed capacity - will raise exception if exceededstack = Stack(capacity=5)stack.push(1)stack.push(2)stack.push(3)
from dsa.queue import Queue# Create a queue with default capacity of 10queue = Queue()# Or create with initial contentsqueue = Queue(contents=[1, 2, 3])
# View front element without removingfront = queue.peek()print(front) # Output: first# Remove and return front elementremoved = queue.dequeue()print(removed) # Output: firstprint(queue.to_ordered_list()) # Output: ['second', 'third']
from dsa.queue import Queuequeue = Queue(capacity=10)queue.enqueue("A")queue.enqueue("B")queue.enqueue("C")print(queue.dequeue()) # Output: A
Arrays provide indexed access to elements. UCX DSA offers Array, DynamicArray, and CircularArray classes.
1
Import and create an Array
from dsa.array import Array# Create empty array with capacity 10arr = Array()# Create with initial contentsarr = Array(contents=[1, 2, 3, 4, 5])# Create with specific capacityarr = Array(capacity=20)
2
Add and access elements
arr = Array()arr.append(10)arr.append(20)arr.append(30)# Access by indexprint(arr[0]) # Output: 10print(arr[2]) # Output: 30# Modify by indexarr[1] = 25print(arr[1]) # Output: 25
3
Insert and delete
# Insert at specific indexarr.insert(1, 15) # Insert 15 at index 1print(arr.to_list()) # Output: [10, 15, 25, 30]# Delete by indexarr.delete(2) # Remove element at index 2print(arr.to_list()) # Output: [10, 15, 30]print(f"Count: {len(arr)}, Capacity: {arr.capacity()}")
# Check if vertex existsprint(graph.has_vertex('A')) # Output: True# Check if edge existsprint(graph.has_edge('A', 'B')) # Output: True# Get adjacent verticesprint(graph.adjacents('B')) # Output: ['A', 'C']# Get all vertices and edgesprint(graph.vertices()) # Output: ['A', 'B', 'C']print(graph.edges()) # Output: [('A', 'B'), ('B', 'C'), ...]# Get graph propertiesprint(graph.order()) # Number of verticesprint(graph.size()) # Number of edges
from dsa.graph import Graph# Efficient for sparse graphsgraph = Graph.create_adjacency_list( directed=False, weighted=False)graph.add_edge('A', 'B')graph.add_edge('B', 'C')print(graph['B']) # Adjacent to B