Reference library

A/B testing & experimentation

User bucketing, experiment metrics, statistical comparison, and rollout guardrails.

9 matches
A/B testing & experimentation medium

Benjamini Hochberg FDR Correction in Python

Implement the Benjamini-HHochberg false discovery rate (FDR) procedure in Python to control the expected proportion of false positives among rejected hypotheses.

fdr multiple testing hypothesis testing
Python
import numpy as np

def benjamini_hochberg(p_values, alpha=0.05):
    p_values = np.array(p_values)
    n = len(p_values)
    sorted_idx = np.argsort(p_values)
    sorted_p = p_values[sorted_idx]
    
    thresholds = (np.arange(1, n + 1) / n) * alpha
    significant = sorted_p <= thresholds
    
    if not significan…
14 0 Open
A/B testing & experimentation easy

How to Build a Simple Binary Protocol Parser Mock in Python

Defines a mock binary protocol with field definitions, encoding, and decoding to simulate network packet parsing for A/B testing and experiment setup.

binary protocol mock
Python
class SimpleProtocol:
    def __init__(self, name, version):
        self.name = name
        self.version = version
        self.fields = []

    def add_field(self, field_name, field_size):
        self.fields.append((field_name, field_size))

    def parse(self, data):
        if len(data) != sum(size for _, size i…
12 0 Open
A/B testing & experimentation easy

How to Calculate Minimum Sample Size for a T-Test in Python

Compute the minimum sample size per group for a two-sample t-test using effect size, significance level, and statistical power.

sample-size statistics ab-testing
Python
import math
from scipy.stats import norm


def min_sample_size(effect_size, alpha=0.05, power=0.8):
    """
    Calculate minimum sample size for a two-sample t-test (equal groups).

    Args:
        effect_size: Cohen's d (standardized mean difference)
        alpha: significance level (Type I error)
        power: …
15 0 Open
A/B testing & experimentation easy

How to Hash a User ID to an Experiment Bucket in Python

Deterministically map a user ID to one of N experiment buckets using MD5 hashing and modulo arithmetic.

hashing ab-testing bucketing
Python
import hashlib

def hash_to_bucket(user_id: str, num_buckets: int = 10) -> int:
    """Deterministically map a user_id to a bucket (0 to num_buckets-1)."""
    digest = hashlib.md5(user_id.encode("utf-8")).hexdigest()
    return int(digest[:8], 16) % num_buckets

if __name__ == "__main__":
    # Mock experiment: split…
14 0 Open
A/B testing & experimentation easy

How to Mock Stratified Assignment by Segment in Python

Simulate stratified assignment for A/B experiments by sampling a fixed proportion of units from each segment, with deterministic seeds for reproducibility.

ab-testing sampling random
Python
import random

def stratified_assignment(segments, seed=None):
    """
    Mock stratified assignment: given a dict of segment -> population size,
    return a dict of segment -> sampled unit ids (deterministic with seed).
    """
    if seed is not None:
        random.seed(seed)
    rng = random.Random(seed)
    res…
12 0 Open
A/B testing & experimentation medium

How to Perform Intent-to-Treat Analysis in Python

Runs an intent-to-treat analysis on mock A/B test data, comparing outcomes by initial group assignment with a t-test for significance.

ab-testing intent-to-treat statistics
Python
import pandas as pd
import numpy as np


def intent_to_treat_analysis(data):
    """Perform intent-to-treat (ITT) analysis.

    ITT compares outcomes based on initial treatment assignment,
    regardless of whether participants actually received the treatment.
    """
    # Create a copy to avoid mutating the origina…
13 0 Open
A/B testing & experimentation easy

How to create a global control holdout group in Python

This code implements a deterministic global control holdout group, randomly selecting a fraction of users to be excluded from feature rollouts for experiment validation.

ab-testing holdout global-control
Python
import random

class GlobalControl:
    def __init__(self, population_size, holdout_fraction=0.2, seed=42):
        random.seed(seed)
        self.population_size = population_size
        self.holdout_fraction = holdout_fraction
        self.holdout_size = int(population_size * holdout_fraction)
        self.holdout_…
11 0 Open
A/B testing & experimentation easy

How to hash user IDs to experiment buckets in Python

Deterministically map a user ID to an experiment bucket using MD5 hashing, ensuring stable and consistent assignment for A/B testing.

hashing ab-testing experiments
Python
import hashlib


def hash_user_to_bucket(user_id: str, num_buckets: int = 10) -> int:
    """Deterministically map a user ID to an experiment bucket (0..num_buckets-1)."""
    digest = hashlib.md5(user_id.encode("utf-8")).hexdigest()
    return int(digest, 16) % num_buckets


if __name__ == "__main__":
    mock_users …
12 0 Open
A/B testing & experimentation easy

Simulate a Ramp Rollout Percentage in Python

Simulates a percentage-based ramp rollout with deterministic seeding, returning success/failure/in-progress counts for a mock user population.

rollout simulation random
Python
import random
from enum import Enum

class RolloutStatus(Enum):
    SUCCESS = "success"
    FAILED = "failed"
    IN_PROGRESS = "in_progress"

def simulate_ramp_rollout(total_users: int, percentage: int, seed: int = 42) -> dict:
    """
    Simulates a mock ramp rollout for a given percentage of users.
    Returns sta…
14 0 Open

Browse by section

Each section groups closely related Python snippets.

A/B testing & experimentation — Python code examples

What you will find here

This page collects a/b testing & experimentation snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.

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.