Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
Validate Sudoku Board Rows Columns and Boxes in Python
Validate a 9x9 Sudoku board by checking that each row, column, and 3x3 box contains the numbers 1 through 9 exactly once.
def validate_sudoku(board):
def is_valid_group(group):
return sorted(group) == list(range(1, 10))
def get_columns():
return [[board[r][c] for r in range(9)] for c in range(9)]
def get_boxes():
boxes = []
for box_row in range(0, 9, 3):
for box_col in range(0, 9,…
How to Topologically Sort a DAG in Python
Compute a valid execution order for tasks with dependencies using Kahn's algorithm in Python.
from collections import defaultdict, deque
def topological_order(dependencies):
graph = defaultdict(list)
in_degree = defaultdict(int)
tasks = set(dependencies.keys())
for task, depends_on in dependencies.items():
for d in depends_on:
graph[d].append(task)
in_degree[t…
Merge K Sorted Lists in Python with heapq
Merge k sorted lists into one sorted list in O(N log k) time using a min-heap of current elements.
import heapq
def merge_k_sorted_lists(lists):
heap = []
for i, lst in enumerate(lists):
if lst: # only push non-empty lists
heapq.heappush(heap, (lst[0], i, 0))
result = []
while heap:
val, list_idx, elem_idx = heapq.heappop(heap)
result.append(val)
if elem…
How to Build a Weighted Random Load Balancer in Python
A Python load balancer mock that distributes requests across servers based on configurable weights using a cumulative weighted random selection algorithm.
import random
from collections import Counter
SERVERS = {
"server-a": 50,
"server-b": 30,
"server-c": 20,
}
def weighted_random_server(servers: dict[str, int]) -> str:
"""Select a server based on its weight (higher weight = more likely)."""
total_weight = sum(servers.values())
rand = random.…
How to Implement the Strategy Pattern in Python
This Python code demonstrates the Strategy design pattern using interchangeable sorting algorithms (bubble sort and quick sort) that can be swapped at runtime.
class SortingStrategy:
def sort(self, data):
raise NotImplementedError
class BubbleSort(SortingStrategy):
def sort(self, data):
result = data.copy()
n = len(result)
for i in range(n):
for j in range(0, n - i - 1):
if result[j] > result[j + 1]:
…
Round Robin Load Balancer in Python
This code simulates round robin load balancing by distributing a list of requests evenly across a list of servers.
def round_robin_servers(requests: list[str], servers: list[str]) -> dict[str, list[str]]:
assignments = {server: [] for server in servers}
for idx, request in enumerate(requests):
server = servers[idx % len(servers)]
assignments[server].append(request)
return assignments
if __name__ == "_…
Redis Leaky Bucket Rate Limiting Mock in Python
Simulates a Redis-backed leaky bucket rate limiter using a local class with continuous leaking and token capacity checks.
import time
from collections import deque
class LeakyBucket:
def __init__(self, capacity, leak_rate):
self.capacity = capacity
self.leak_rate = leak_rate
self.water = 0.0
self.timestamp = time.time()
self.history = deque()
def allow(self):
current = time.time(…
GCRA generic cell rate algorithm in Python
Mock implementation of the Generic Cell Rate Algorithm (GCRA) for traffic shaping and rate limiting.
from collections import deque
import time
class GCRA:
def __init__(self, rate, burst):
self.tau = burst
self.T = rate
self.t = 0
self.LCT = 0
def add_cell(self, arrival_time):
if arrival_time <= self.t:
return False
arrived_early = (arrival_time - s…
Token bucket rate limiter in Python (in-memory)
Implement a thread-safe in-memory token bucket rate limiter that throttles requests based on a steady refill rate.
import time
import threading
class TokenBucket:
def __init__(self, capacity, refill_rate, refill_interval=1.0):
self.capacity = capacity
self.tokens = capacity
self.refill_rate = refill_rate
self.refill_interval = refill_interval
self.last_refill = time.monotonic()
…
How to Build a DAG Execution Stage Calculator in Python
Computes the execution stages of a directed acyclic graph (DAG) by grouping nodes that become ready simultaneously using topological sorting with Kahn's algorithm.
from collections import defaultdict, deque
def get_stages(edges):
"""Return list of stages, where each stage is a list of nodes
that become ready at the same time in a DAG."""
graph = defaultdict(list)
in_degree = defaultdict(int)
nodes = set()
for src, dst in edges:
graph[src].appen…
Training Pipeline Orchestration Mock DAG in Python
Build a mock DAG orchestrator that runs ML pipeline stages in dependency order using topological sorting (Kahn's algorithm).
from collections import deque
from dataclasses import dataclass, field
@dataclass
class DAGNode:
name: str
task: callable
dependencies: list[str] = field(default_factory=list)
class MockDAG:
def __init__(self, nodes: list[DAGNode]):
self.nodes = {n.name: n for n in nodes}
self.execu…
How to simulate a contextual bandit in Python
Simulate a contextual multi-armed bandit with random features and epsilon-greedy action selection in Python.
import random
class ContextualBandit:
def __init__(self, n_actions=3, n_features=4):
self.n_actions = n_actions
self.n_features = n_features
self.theta = [random.random() for _ in range(n_actions * n_features)]
def mock_context(self):
return [random.uniform(-1, 1) for _ in ra…
Thompson Sampling Mock Bandit in Python
Implement a Thompson sampling multi-armed bandit to explore and exploit reward probabilities across multiple options, updating Beta distributions over time.
import random
class ThompsonSamplingBandit:
def __init__(self, num_arms, alpha=1.0, beta=1.0):
self.num_arms = num_arms
self.alpha = [alpha] * num_arms
self.beta = [beta] * num_arms
def select_arm(self):
samples = [random.betavariate(a, b) for a, b in zip(self.alpha, self.beta…
UCB1 Bandit Algorithm in Python
This code implements the UCB1 multi-armed bandit algorithm, balancing exploration and exploitation to identify the best arm while maximizing cumulative reward.
import math
import random
def ucb1(means, n_iterations=1000, exploration_weight=2.0):
"""Run UCB1 bandit algorithm on arms with given true means."""
n_arms = len(means)
counts = [0] * n_arms
rewards = [0.0] * n_arms
for t in range(1, n_iterations + 1):
# UCB1 selection
if t <…
Simulate a GIN Index for JSONB in Python
Build a mock Generalized Inverted Index (GIN) that flattens JSON documents into key-value tokens for fast lookup queries, mimicking PostgreSQL JSONB indexing.
import json
import random
from collections import defaultdict
# Mock GIN (Generalized Inverted Index) for JSONB key-value pairs
class GINIndex:
def __init__(self):
self.posting_lists = defaultdict(list) # token -> list of doc_ids
def index(self, doc_id, json_obj):
"""Index a JSON documen…
Browse by section
Each section groups closely related Python snippets.
Guide: free Python code samples library
Copy-ready Python snippets for learners and developers
PythonSkillset code samples are short, focused examples organised by topic and difficulty. Every snippet is server-rendered HTML — readable by search engines and easy to copy. Open any sample, read the notes, copy the code, then press Try in editor to run it in the browser with Pyodide.
How to use this library
- Pick a topic section — strings, lists, files, functions, and more
- Open a sample, read How it works, and copy the code block
- Run it in the IDE, tweak values, then take a related quiz or tutorial lesson
Samples vs tutorials and challenges
Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.