Reference library

Python Code Samples

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

6 matches
AI & LLM integration patterns medium

How to Repair Malformed JSON Braces Heuristically in Python

Heuristically fix malformed JSON by balancing braces and quotes, using a stack-based approach to add missing closing characters.

json repair heuristic
Python
import json
import re

def repair_json(text: str) -> str:
    """Heuristically repair malformed JSON by balancing braces and quotes."""
    # Trim whitespace and handle leading/trailing garbage
    text = text.strip()
    
    # Remove common non-JSON decorations
    text = re.sub(r'^(
13 0 Open
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…
13 0 Open
System design patterns medium

Implement a Consistent Hash Ring in Python

Build a minimal consistent hash ring with virtual nodes to map keys to servers stably as nodes are added or removed.

consistent-hashing hashing distributed-systems
Python
import hashlib
import bisect


class ConsistentHashRing:
    def __init__(self, nodes=None, replicas=3):
        self.replicas = replicas
        self.ring = {}
        self.sorted_keys = []
        if nodes:
            for node in nodes:
                self.add_node(node)

    def _hash(self, key):
        return i…
15 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…
14 0 Open
A/B testing & experimentation medium

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.

ucb1 bandit ab-testing
Python
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 <…
14 0 Open
Database scaling & optimization medium

How to Implement Consistent Hashing in Python

Build a consistent hash ring in Python that distributes keys across nodes and minimizes remapping when nodes are added or removed.

consistent-hashing distributed-systems sharding
Python
import hashlib
from bisect import bisect_right


class ConsistentHashRing:
    def __init__(self, nodes, replicas=3):
        self.replicas = replicas
        self.ring = {}
        self.sorted_keys = []
        for node in nodes:
            self.add_node(node)

    def _hash(self, key):
        return int(hashlib.md…
15 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.