Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
Cosine Similarity to Retrieve Top K Chunks in Python
Compute cosine similarity between a query vector and a list of chunk vectors, then return the indices and scores of the top k most similar chunks.
import numpy as np
from numpy.linalg import norm
def cosine_similarity(vec1, vec2):
return np.dot(vec1, vec2) / (norm(vec1) * norm(vec2))
def retrieve_top_k(query_vec, chunk_vectors, k=3):
similarities = [cosine_similarity(query_vec, vec) for vec in chunk_vectors]
top_indices = sorted(range(len(similarit…
How to Create a Mock Text Embedding with Hash in Python
Generate deterministic mock text embeddings using SHA-256 hashing and numpy, producing normalized vectors for similarity testing without an LLM.
import hashlib
import numpy as np
def mock_embed(text: str, dim: int = 10, seed: int = 42) -> np.ndarray:
"""Generate a deterministic mock embedding using a hash function.
Args:
text: Input text to embed
dim: Dimension of the output vector
seed: Seed for reproducibility
R…
How to Vectorize a Function with a Pure Python Fallback
Create a decorator that calls a scalar function directly for a single value and routes list inputs to a pure-Python fallback for vectorized processing without NumPy.
import math
def fallback_vectorize(func, fallback=None):
"""Vectorize a scalar function with a pure-Python fallback for lists."""
if fallback is None:
fallback = lambda x: [func(i) for i in x]
def wrapped(*args):
if len(args) == 1 and isinstance(args[0], (list, tuple)):
retur…
How to Compute a Confusion Matrix in Python
Compute a multi-class confusion matrix from true and predicted labels using pure Python dictionaries and nested lists, then format it for readable output.
from collections import defaultdict
def compute_confusion_matrix(y_true, y_pred, labels):
"""Compute confusion matrix using Python dicts and nested lists."""
label_index = {label: i for i, label in enumerate(labels)}
matrix = [[0] * len(labels) for _ in range(len(labels))]
for true, pred in zip(y…
How to Detect Data Drift with PSI in Python
Calculate the Population Stability Index (PSI) in Python to compare expected vs actual distributions and detect data drift in machine learning pipelines.
import numpy as np
def calculate_psi(expected, actual, buckets=10):
"""Calculate Population Stability Index (PSI) between two distributions."""
# Create bucket edges based on expected distribution percentiles
edges = np.percentile(expected, np.linspace(0, 100, buckets + 1))
edges[-1] = np.inf # Ensur…
How to Run Batch Predictions with a Mock Model in Python
Build a lightweight mock model class and run predictions across a batch of samples, returning results as a plain Python list.
import numpy as np
class MockModel:
def __init__(self, weights):
self.weights = np.array(weights)
def predict(self, X):
return X @ self.weights
def predict_batch(model, batch):
"""Run predictions for a batch of samples and return results as a list."""
return model.predict(np.array(ba…
How to do feature selection with VarianceThreshold in Python
This code demonstrates how to use scikit-learn's VarianceThreshold to remove low-variance features from a NumPy array, keeping only those that vary enough to be useful for modeling.
import numpy as np
from sklearn.feature_selection import VarianceThreshold
def main():
# Mock dataset: 4 samples, 5 features
X = np.array([
[0.1, 0.2, 1.0, 1.0, 0.5],
[0.2, 0.2, 0.0, 1.0, 0.4],
[0.1, 0.2, 1.0, 1.0, 0.6],
[0.3, 0.2, 1.0, 0.0, 0.5]
])
# Select features w…
One Hot Encode Categories in Python
Convert a list of categorical strings into one-hot encoded numeric vectors using pure Python and NumPy.
import numpy as np
categories = ["red", "green", "blue", "red", "blue", "green", "red"]
unique = sorted(set(categories))
lookup = {cat: i for i, cat in enumerate(unique)}
one_hot = []
for cat in categories:
row = [0] * len(unique)
row[lookup[cat]] = 1
one_hot.append(row)
print("Categories:", categories…
Train Logistic Regression From Scratch in Python
Trains a binary logistic regression model using gradient descent on mock data, printing learned weights and probabilities.
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…
Bonferroni Correction in Python
Applies the Bonferroni correction to a list of p-values to control the family-wise error rate when performing multiple comparisons.
import numpy as np
def bonferroni_correction(p_values, alpha=0.05):
"""Apply Bonferroni correction to a list of p-values."""
n = len(p_values)
corrected_alpha = alpha / n
significant = [p < corrected_alpha for p in p_values]
return corrected_alpha, significant
if __name__ == "__main__":
# Moc…
Bootstrap Confidence Interval in Python
Estimates a confidence interval for a statistic (like the mean) using bootstrap resampling in pure Python.
import random
def bootstrap_ci(data, statistic, n_bootstraps=1000, ci_level=0.95, seed=42):
random.seed(seed)
n = len(data)
boot_stats = []
for _ in range(n_bootstraps):
sample = [random.choice(data) for _ in range(n)]
boot_stats.append(statistic(sample))
boot_stats.sort()
l…
Check Covariate Balance in Python
Compute standardized mean differences and KS tests to check covariate balance between treatment and control groups in Python.
import numpy as np
from scipy import stats
def balance_check(treatment, covariate):
"""Check covariate balance between treatment and control groups."""
treat_vals = covariate[treatment == 1]
control_vals = covariate[treatment == 0]
# Standardized mean difference
pooled_std = np.sqrt((np.var(t…
Delta Method for Ratio Metrics in A/B Testing with Python
Computes the confidence interval for the difference between two ratio metrics using the delta method, with mock A/B test data.
import numpy as np
from scipy.stats import norm
def delta_method_ratio_delta(control: np.ndarray, treatment: np.ndarray, confidence: float = 0.95):
"""Estimate confidence interval for ratio metric using delta method.
Args:
control: numerator/denominator pairs from control group (n x 2 array)
…
How to Compute CUPED Variance Reduction in Python
Implement CUPED in Python to reduce variance of A/B test treatment effect estimates using pre-experiment covariates.
import numpy as np
def compute_cuped_reduction(control, variant, covariate):
"""
Compute variance reduction using CUPED (Controlled Experiment with
Pre-Experiment Data). Uses pre-experiment covariate values to
reduce variance of the treatment effect estimate.
"""
control = np.asarray(control, …
How to Compute Mann-Whitney U Test in Python
Compute the Mann-Whitney U statistic and p-value manually in Python with tie correction and a normal approximation for independent samples.
import numpy as np
from scipy import stats
def mann_whitney_u_mock(sample_a, sample_b):
"""Compute Mann-Whitney U and p-value manually."""
# Combine and rank
combined = sample_a + sample_b
n_a, n_b = len(sample_a), len(sample_b)
n_total = n_a + n_b
# Rank with ties handling (average ranks…
How to Conduct a Two-Sample T-Test in Python
Performs Welch's t-test for two independent samples, computing the t-statistic, degrees of freedom, and p-value using NumPy and SciPy.
import numpy as np
def two_sample_t_test(sample1, sample2):
"""Perform Welch's t-test for two independent samples."""
n1, n2 = len(sample1), len(sample2)
mean1, mean2 = np.mean(sample1), np.mean(sample2)
var1, var2 = np.var(sample1, ddof=1), np.var(sample2, ddof=1)
# Standard error of difference
…
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.
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…
How to Generate an Orthogonal Array for A/B Testing in Python
Generate a mock orthogonal array for multi-layer experiments with NumPy, ensuring balanced level combinations across experiment groups.
import numpy as np
def orthogonal_mock_layers(n_experiments: int, n_layers: int, n_levels: int) -> np.ndarray:
"""Generate an orthogonal array for multi-layer experiment design using base-level logic."""
ortho = np.indices((n_levels,) * n_layers).reshape(n_layers, -1).T
ortho = ortho % n_levels # Classic…
Synthetic Control in Python: Mock Example
Implements synthetic control from scratch: learns donor weights via ridge regression on pre-period data, then predicts a counterfactual for the treated unit.
import numpy as np
class SyntheticControl:
def __init__(self, data, treated_index, pre_periods, post_periods):
self.data = np.array(data, dtype=float)
self.treated_index = treated_index
self.pre_periods = pre_periods
self.post_periods = post_periods
def fit_weights(sel…
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.