Reference library

Python Code Samples

Medium snippets you can copy, study, and run in the browser editor.

23 matches
Algorithms & data structures medium

Find the Duplicate Number in Python Using Floyd's Cycle Detection

Detects the duplicate integer in an array of n+1 numbers (values 1 to n) in O(n) time and O(1) space using Floyd's cycle detection algorithm applied to a linked-list model.

floyd-cycle duplicate-number two-pointers
Python
def find_duplicate(nums):
    slow = nums[0]
    fast = nums[0]
    
    # Phase 1: Find intersection point of the cycle
    while True:
        slow = nums[slow]
        fast = nums[nums[fast]]
        if slow == fast:
            break
    
    # Phase 2: Find the start of the cycle (the duplicate)
    slow = nums[0…
14 0 Open
Data pipelines & processing medium

How to perform a star schema join in Python

Denormalize mock fact and dimension tables by building lookup dicts and enriching each sales fact with customer, product, and date attributes.

star-schema data-joins dimensional-modeling
Python
from datetime import date

# Mock dimension tables
customers = [
    {"customer_id": 1, "name": "Alice", "city": "New York"},
    {"customer_id": 2, "name": "Bob", "city": "Los Angeles"},
    {"customer_id": 3, "name": "Carol", "city": "Chicago"},
]

products = [
    {"product_id": 101, "name": "Laptop", "category": "…
12 0 Open
Testing & modern typing medium

How to Mock a Factory Boy Model Instance in Python

Create a factory boy factory, then patch its Meta.model with a Mock to control instance behavior in tests.

factory-boy mocking unit-testing
Python
import factory
from dataclasses import dataclass
from unittest.mock import Mock, patch
import builtins


@dataclass
class User:
    name: str
    age: int


class UserFactory(factory.Factory):
    class Meta:
        model = User

    name = "Alice"
    age = 30


def get_user_name(user):
    return user.name


def ma…
15 0 Open
System design patterns medium

Domain Driven Design Aggregate Root Example in Python

Model an Order as an aggregate root with invariants enforced through methods, demonstrating DDD principles in Python.

ddd aggregate-root object-oriented
Python
from __future__ import annotations
from dataclasses import dataclass
from typing import List, Optional
from uuid import uuid4


class Money:
    def __init__(self, amount: float, currency: str = "USD"):
        self.amount = amount
        self.currency = currency

    def __add__(self, other: Money) -> Money:
       …
12 0 Open
System design patterns medium

How to Implement CQRS with Separate Read and Write Models in Python

Implements Command Query Responsibility Segregation (CQRS) by splitting data into separate write and read models with dedicated repositories, using dataclasses for structure.

cqrs dataclasses repositories
Python
from dataclasses import dataclass, field
from typing import List, Dict, Optional


@dataclass
class OrderWriteModel:
    order_id: int
    customer: str
    items: List[str] = field(default_factory=list)

    def add_item(self, item: str) -> None:
        self.items.append(item)


@dataclass
class OrderReadModel:
    …
14 0 Open
System design patterns medium

How to Implement a Simple MVVM Binding Mock in Python

A minimal Python implementation of the MVVM pattern, mocking data binding so views auto-update when the view model changes.

mvvm binding observer pattern
Python
class BindingMock:
    def __init__(self, view_model):
        self.view_model = view_model
        self.subscribers = []

    def bind(self, property_name, callback):
        self.subscribers.append((property_name, callback))

    def set(self, property_name, value):
        setattr(self.view_model, property_name, va…
18 0 Open
Streaming & messaging medium

How to mock a CQRS projector read model update in Python

Build a CQRS projector class that maintains denormalized read models by applying domain events in a mock order-processing service.

cqrs projector read-model
Python
from dataclasses import dataclass, field
from typing import Dict, List, Optional


@dataclass
class OrderReadModel:
    order_id: str
    customer_name: str
    total: float
    status: str = "pending"
    items: List[Dict] = field(default_factory=list)

    def apply_event(self, event_type: str, payload: Dict) -> Non…
11 0 Open
Reliability & rate limiting medium

At Least Once with Idempotent Consumer in Python

Implements a thread-safe idempotent consumer that processes each unique message exactly once, even when a producer sends duplicates under an at-least-once delivery model.

idempotency at-least-once threading
Python
import threading
import time
import uuid
from collections import Counter


class IdempotentConsumer:
    def __init__(self):
        self.processed = set()
        self._lock = threading.Lock()

    def consume(self, message_id, payload):
        with self._lock:
            if message_id in self.processed:
          …
15 0 Open
Microservices patterns medium

How to Build an Anti-Corruption Layer in Python

Translate messy legacy system data into a clean domain model using an anti-corruption layer in Python.

anti-corruption microservices data-transformation
Python
class MockLegacySystem:
    """Simulates a legacy system with messy data formats."""
    def get_user_data(self):
        # Legacy format: fields are abbreviated and types are inconsistent
        return {
            "usr_id": "USR-123",
            "usr_nm": "john_doe",
            "email_addrs": "John.Doe@example.c…
15 0 Open
Microservices patterns medium

How to Mock a Choreography Saga in Python

Simulate a choreography-based saga with event envelopes, status tracking, and compensating actions to model distributed transactions.

saga microservices events
Python
import json
from dataclasses import dataclass, asdict
from typing import List, Optional
from enum import Enum


class SagaStatus(Enum):
    PENDING = "PENDING"
    COMPLETING = "COMPLETING"
    COMPLETED = "COMPLETED"
    FAILED = "FAILED"


@dataclass
class EventEnvelope:
    event_type: str
    order_id: str
    sta…
13 0 Open
ML engineering pipelines medium

Bayesian Optimization in Python: A Simplified Mock Implementation

A toy Bayesian optimization loop with a Gaussian process prior, expected improvement acquisition, and noisy sampling to find a function's minimum.

bayesian-optimization gaussian-process hyperparameter-tuning
Python
import random
import math

class BayesianOptimizer:
    def __init__(self, noise=0.1):
        self.noise = noise
        self.observations = []
    
    def objective(self, x):
        return (math.sin(3*x) + 0.5*x) / (1 + x**2)
    
    def gaussian_process_prior(self, x1, x2, length_scale=0.5):
        return math.…
12 0 Open
ML engineering pipelines medium

How to Build an sklearn Pipeline with ColumnTransformer in Python

A mock example showing how to chain preprocessing and a regression model into a single sklearn Pipeline, scaling numeric features and one-hot encoding categorical features with ColumnTransformer.

sklearn pipeline columntransformer
Python
import numpy as np
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.pipeline import Pipeline
from sklearn.linear_model import LinearRegression

# Mock dataset
X = np.array([[1, 'red'], [2, 'blue'], [3, 'red'], [4, 'green'], [5, 'blue']], dtype=o…
13 0 Open
ML engineering pipelines medium

How to Create a Mock ONNX Model in Python

Build and export a minimal mock ONNX model with a Reshape and Gemm layer using the onnx helper API.

onnx model-export mlops
Python
import onnx
import numpy as np
from onnx import helper, TensorProto

def create_mock_model():
    # Define input and output tensors
    input_tensor = helper.make_tensor_value_info('input', TensorProto.FLOAT, [1, 3, 224, 224])
    output_tensor = helper.make_tensor_value_info('output', TensorProto.FLOAT, [1, 10])

   …
16 0 Open
ML engineering pipelines medium

How to Mock MLflow Model Registration in Python

Build a lightweight in-memory mock of MLflow's MlflowClient to test model registration, versioning, and stage transitions without a tracking server.

mlflow mocking model-registry
Python
from mlflow.tracking import MlflowClient
from mlflow.entities import ModelVersion, Model


class MockMlflowClient:
    """Minimal mock of MlflowClient's model registration methods."""
    
    def __init__(self):
        self.registered_models = {}
        self.model_versions = {}
    
    def register_model(self, mod…
14 0 Open
ML engineering pipelines medium

How to Mock ROC AUC in Python

Compute ROC AUC from scratch in Python using pairwise comparisons between positive and negative score distributions, ideal for testing ML models without sklearn.

machine-learning model-evaluation auc
Python
import random
from math import comb


def mock_roc_auc(scores, labels):
    """Compute mock ROC AUC by simulating a classifier's score distribution."""
    random.seed(42)
    n = len(labels)
    pos_scores = [scores[i] for i in range(n) if labels[i] == 1]
    neg_scores = [scores[i] for i in range(n) if labels[i] == …
12 0 Open
ML engineering pipelines medium

How to Stage ML Model Workflows with Python Classes

Defines a Stage class to model ML pipeline stages with variants and mocks, printing grammar for Model, Staging, and Production stages.

ml-pipelines stages model-deployment
Python
class Stage:
    def __init__(self, name):
        self.name = name
        self.mocks = []
        self.variants = []

    def add_mock(self, mock_name):
        self.mocks.append(mock_name)

    def add_variant(self, variant_name, productions=()):
        self.variants.append((variant_name, list(productions)))

    …
12 0 Open
ML engineering pipelines medium

How to Train a Gradient Boosting Regressor in Python

Build and evaluate a scikit-learn GradientBoostingRegressor on a synthetic dataset, printing test MSE and feature importances.

sklearn gradient-boosting regression
Python
import numpy as np
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.metrics import mean_squared_error

def train_gradient_boosting_mock():
    # Toy regression dataset
    np.random.seed(42)
    X = np.random.rand(100, 3) * 10
    y = 2 * X[:, 0] - 1.5 * X[:, 1] + 0.5 * X[:, 2] + np.random.normal(0,…
13 0 Open
ML engineering pipelines medium

K-Fold Cross Validation in Python: A Simple Implementation

Implements k-fold cross validation from scratch, splitting data into folds and computing MSE scores for a baseline mean-predictor model.

cross-validation ml model-evaluation
Python
import random
from statistics import mean


def cross_validation_scores(data, labels, k=5, seed=42):
    random.seed(seed)
    indices = list(range(len(data)))
    random.shuffle(indices)
    fold_size = len(indices) // k
    folds = []
    for i in range(k):
        if i == k - 1:
            folds.append(indices[i *…
16 0 Open
ML engineering pipelines medium

Train Logistic Regression From Scratch in Python

Trains a binary logistic regression model using gradient descent on mock data, printing learned weights and probabilities.

logistic-regression machine-learning gradient-descent
Python
import numpy as np

# Mock data: 2 features, binary classification
X = np.array([[1, 2], [2, 3], [3, 4], [4, 5], [5, 6]])
y = np.array([0, 0, 1, 1, 1])

# Add bias term (column of ones)
X_b = np.c_[np.ones((X.shape[0], 1)), X]

# Initialize parameters
theta = np.zeros(X_b.shape[1])

# Hyperparameters
learning_rate = 0…
14 0 Open
A/B testing & experimentation medium

How to Create an Interrupted Time Series Mock in Python

Generate simulated interrupted time series data with a pre/post-intervention trend, level shift, and noise to test segmented regression models.

interrupted-time-series simulation numpy
Python
import numpy as np

# Mock interrupted time series data
np.random.seed(42)
n_pre = 50
n_post = 50
time = np.arange(0, n_pre + n_post)

# Pre-intervention: linear trend + noise
pre_trend = 0.05 * time[:n_pre] + np.random.normal(0, 0.5, n_pre)

# Post-intervention: new slope + level shift + noise
post_trend = 0.05 * tim…
15 0 Open
Database scaling & optimization medium

How to Simulate Distributed Transactions in Python with a Mock

Model distributed transaction behavior with a mock Transaction class that supports commit, rollback, and failure simulation.

transactions mock database
Python
class Transaction:
    def __init__(self, id):
        self.id = id
        self.operations = []
        self.committed = False

    def add_operation(self, op, data):
        self.operations.append((op, data))

    def commit(self):
        if not self.operations:
            raise ValueError("No operations to commit…
13 0 Open
Database scaling & optimization medium

Mock CQRS Read/Write Split in Python

Separate order mutations from queries using a read model and write model to mock CQRS-style separation of concerns.

cqrs read-write dataclass
Python
from dataclasses import dataclass, field
from typing import List, Dict


@dataclass
class Order:
    id: int
    amount: float
    status: str = "pending"


class OrderWriteModel:
    """Handles all mutations (writes) to orders."""

    def __init__(self):
        self._orders: Dict[int, Order] = {}
        self._next…
12 0 Open
Production deployment patterns medium

How to Mock Image Signing Cost in Python

Create a deterministic mock signing cost calculator that predicts resource usage for image signatures before real signing infrastructure is staged.

mock signing cost-model
Python
import math
import struct


def sign_image_cost(image_signature: bytes) -> int:
    """Deterministic mock signing cost based on image signature bytes."""
    if not image_signature:
        raise ValueError("Empty image signature")
    digest = 0
    for byte in image_signature:
        digest = (digest * 31 + byte) &…
14 0 Open

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

  1. Pick a topic section — strings, lists, files, functions, and more
  2. Open a sample, read How it works, and copy the code block
  3. 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.