Reference library

Python Code Samples

Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.

13 matches
Automation & scripting medium

How to Implement a Weighted DNS Resolver with Failover in Python

Simulates a weighted DNS load balancer that distributes traffic across IPs by weight and automatically fails over when a server is marked unhealthy.

dns load-balancing failover
Python
import random
import time

class WeightedDNSResolver:
    def __init__(self, records):
        self.records = records  # list of (ip, weight)
        self.total_weight = sum(weight for _, weight in records)
        self.failed_ips = set()

    def resolve(self):
        available = [(ip, weight) for ip, weight in self…
12 0 Open
Cloud + Python easy

How to Mock ELB Target Health Status in Python

Simulate AWS Elastic Load Balancer target health checks with a Python dict that mutates status and healthy host counts.

elb mock healthcheck
Python
from random import randint

def elb_target_mock_status(target_id, healthy=True):
    targets = {
        1: {"Id": "i-001", "Status": "healthy", "Port": 80, "HealthyHostCount": 1},
        2: {"Id": "i-002", "Status": "unhealthy", "Port": 80, "HealthyHostCount": 0},
        3: {"Id": "i-003", "Status": "healthy", "Por…
12 0 Open
System design patterns easy

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.

python how build
Python
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.…
13 0 Open
System design patterns easy

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.

load-balancing round-robin system-design
Python
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__ == "_…
12 0 Open
Streaming & messaging medium

How to Mock a Kafka Rebalance Listener in Python

Simulate Kafka consumer rebalance callbacks (on_partitions_revoked and on_partitions_assigned) with a mock consumer to test listener logic.

kafka rebalance mocking
Python
import time
from collections import defaultdict


class MockKafkaConsumer:
    def __init__(self):
        self.assignments = defaultdict(list)
        self.rebalances = 0

    def assign(self, partitions):
        self.rebalances += 1
        self.assignments.clear()
        for partition in partitions:
            s…
14 0 Open
Microservices patterns easy

How to Mock a Server-Side Load Balancer in Python

A simple Python class that mimics a server-side load balancer with round-robin, random, and least-connections selection strategies.

load-balancer microservices simulation
Python
import itertools
import random

class LoadBalancer:
    def __init__(self, servers=None):
        self.servers = servers if servers else ["server1", "server2", "server3"]
        self.counter = itertools.count(1)

    def round_robin(self):
        return next(self.counter) % len(self.servers)

    def random_selectio…
12 0 Open
Microservices patterns easy

How to implement round-robin load balancing in Python

Implement a client-side round-robin load balancer that distributes requests sequentially across a list of mock servers using itertools.cycle.

load balancing round robin microservices
Python
import itertools
import random


class MockServer:
    def __init__(self, name):
        self.name = name

    def handle_request(self, request_id):
        return f"Server {self.name} handled request #{request_id}"


class RoundRobinLoadBalancer:
    def __init__(self, servers):
        self.servers = servers
       …
13 0 Open
A/B testing & experimentation medium

Check Covariate Balance in Python

Compute standardized mean differences and KS tests to check covariate balance between treatment and control groups in Python.

covariate balance ab-testing
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…
13 0 Open
A/B testing & experimentation medium

Epsilon Greedy Bandit Mock in Python

A simple epsilon-greedy multi-armed bandit simulation that balances exploration and exploitation to estimate true means of several Bernoulli-like reward distributions.

bandit epsilon-greedy exploration
Python
import random


class Bandit:
    def __init__(self, true_mean):
        self.true_mean = true_mean
        self.estimated_mean = 0.0
        self.n_pulls = 0

    def pull(self):
        return random.gauss(self.true_mean, 1.0)

    def update(self, reward):
        self.n_pulls += 1
        self.estimated_mean += (r…
11 0 Open
A/B testing & experimentation medium

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.

ab-testing orthogonal-array numpy
Python
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…
13 0 Open
Database scaling & optimization hard

B-Tree Insert and In-Order Traversal in Python

Simulates a B-tree (order 2) with insert and split logic, then prints keys in sorted order via in-order traversal.

b-tree tree data-structure
Python
class BTreeNode:
    def __init__(self, leaf=False):
        self.leaf = leaf
        self.keys = []
        self.children = []

    def is_full(self, t):
        return len(self.keys) == 2 * t - 1


class BTree:
    def __init__(self, t=2):
        self.t = t
        self.root = BTreeNode(leaf=True)

    def insert(s…
13 0 Open
Database scaling & optimization medium

Consistent Hashing with Virtual Buckets in Python

This code maps many virtual buckets onto a few physical buckets using a consistent hashing ring, ensuring balanced distribution with minimal remapping when physical buckets change.

consistent-hashing virtual-buckets sharding
Python
import random

class VirtualBuckets:
    """Maps many virtual buckets onto few physical buckets using consistent hashing."""
    
    def __init__(self, physical_buckets, virtual_factor=100):
        self.physical = list(physical_buckets)
        self.virtual_factor = virtual_factor
        self.ring = []
        self…
13 0 Open
Database scaling & optimization easy

Rebalance Shard Ranges Across Nodes in Python

A mock rebalancing function that shuffles shard ranges and distributes them evenly across nodes using round-robin assignment.

sharding rebalancing dataclass
Python
import random
from dataclasses import dataclass

@dataclass
class Shard:
    id: int
    start: int
    end: int

def rebalance_shards(shards: list[Shard], node_count: int) -> dict[int, list[Shard]]:
    """Mock rebalancing of shard ranges across nodes."""
    all_ranges = [(s.start, s.end) for s in shards]
    random…
10 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.