Reference library

Python Code Samples

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

14 matches
Algorithms & data structures medium

Implement Insert Delete GetRandom O(1) in Python

Build a RandomizedSet class that supports insert, delete, and get_random in average O(1) time using a list and a dictionary mapping values to indices.

randomized-set o1-lookup hash-map
Python
import random

class RandomizedSet:
    def __init__(self):
        self.values = []
        self.index_map = {}

    def insert(self, val):
        if val in self.index_map:
            return False
        self.index_map[val] = len(self.values)
        self.values.append(val)
        return True

    def delete(self…
12 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
Testing & modern typing medium

How to Test Properties with Random Inputs in Python

Write a simple property-based test in Python using random string generation to verify that string invariants like reverse-twice identity and uppercase idempotence always hold.

property-based-testing random testing
Python
import random
import string


def generate_random_string(length: int) -> str:
    """Generate a random alphanumeric string of given length."""
    chars = string.ascii_letters + string.digits
    return "".join(random.choice(chars) for _ in range(length))


def reverse_twice_is_identity(s: str) -> bool:
    """Propert…
12 0 Open
Testing & modern typing medium

How to Use Hypothesis Strategies for Lists of Text in Python

Generate random lists of non-empty strings with Hypothesis and verify that joining them with a comma-and-space separator meets expected length and containment invariants.

hypothesis property-based-testing strategies
Python
from hypothesis import given, strategies as st
from hypothesis import example


@given(st.lists(st.text(min_size=1, max_size=10), min_size=1, max_size=5))
def test_joined_string_length(items):
    """Each text is non-empty; a joined string should be at least as long
    as the number of items (separator adds character…
13 0 Open
Caching & Redis medium

How to Add TTL Jitter to Cache Expiration in Python

A Python decorator that adds random jitter to cache TTLs, staggering expiration times to prevent cache avalanche.

cache ttl jitter
Python
import random
import time
from functools import wraps

def add_jitter(ttl: float, jitter_range: float = 0.1) -> float:
    """Add random jitter (as % of TTL) to stagger cache expiration and prevent avalanche."""
    jitter = random.uniform(-jitter_range, jitter_range)
    return ttl * (1 + jitter)

def cache_with_jitt…
15 0 Open
Caching & Redis medium

How to Implement Probabilistic Early Expiration in Python

A Python mock of probabilistic early expiration for caches, using a heap-based expiry queue and random eviction to approximate cache stampede protection.

caching expiration heap
Python
import heapq
import random
import time


class ProbabilisticEarlyExpirationMock:
    def __init__(self, capacity=1024, expiration_probability=0.1):
        self.capacity = capacity
        self.expiration_probability = expiration_probability
        self._items = {}
        self._expiry_heap = []
        self._next_id…
14 0 Open
Reliability & rate limiting medium

Retry with Exponential Backoff and Jitter in Python

A decorator-style retry wrapper that retries a flaky function with exponential backoff plus random jitter, then raises after the last attempt fails.

retry backoff jitter
Python
import random
import time

def retry_with_backoff(func, max_retries=3, base_delay=0.5, max_jitter=0.1):
    for attempt in range(max_retries + 1):
        try:
            return func()
        except Exception as e:
            if attempt == max_retries:
                raise
            delay = base_delay * (2 ** at…
14 0 Open
Observability & SRE medium

How to Track Cache Hit Ratio in Python

Simulate an LRU cache with hit/miss tracking and compute a real-time hit ratio from random access patterns.

cache lru hit-ratio
Python
import random
import time
from collections import OrderedDict

class LRUCache:
    def __init__(self, capacity: int):
        self.cache = OrderedDict()
        self.capacity = capacity
        self.hits = 0
        self.misses = 0

    def get(self, key):
        if key in self.cache:
            self.hits += 1
     …
13 0 Open
Microservices patterns medium

How to Mock Service Call Timeouts in Python

Simulate service calls with configurable timeouts using Mock to patch sleep and randomness, covering success and timeout cases.

microservices testing timeout
Python
import time
from unittest.mock import Mock, patch

# Simulate a service call with configurable timeout
def call_service(service_name, timeout=5):
    """Mock a service call that may time out."""
    start = time.time()
    print(f"Calling {service_name}...")
    
    # Simulate service latency (randomized for realism)…
16 0 Open
Big data & Spark medium

Skew Join Salting Key in Python (Demo)

Demonstrates skew join salting by expanding a smaller side with salt keys and matching rows on the larger side via random salt assignment.

skew join salting distributed
Python
import random


def skew_join_salting_key(left_df, right_df, salt_range=4):
    """
    Demonstrates skew join salting: expand the smaller side with salt keys,
    then attach a salt key to each row on the larger side.
    Returns a list of (left, right, salt) tuples.
    """
    skewed_left = []
    for row in left_d…
14 0 Open
A/B testing & experimentation medium

Check Sample Ratio Mismatch in Python

Estimates the probability that a simple random sample's proportion differs from the population proportion by more than 10% using simulation.

simulation statistics ab-testing
Python
import random


def sample_ratio_mismatch(population_size: int, sample_size: int, p: float) -> float:
    """
    Estimate the probability that a simple random sample's proportion
    differs from the population proportion by more than 10%.
    """
    total_counts = [0, 0]
    for _ in range(10000):
        sample = …
15 0 Open
A/B testing & experimentation medium

How to Simulate Geo Experiments in Python

Build a mock geo experiment simulator with ramp-up/down periods, measuring weekly lift between treatment and control markets.

geo-experiment ab-testing simulation
Python
import random
import math
from dataclasses import dataclass

@dataclass
class GeoMarket:
    name: str
    base_demand: float
    geo_coefficient: float

def simulate_geo_experiment(markets, weeks=12, control_weeks=6):
    """
    Simulates a geo experiment with ramp-up and ramp-down periods.
    Returns weekly lift p…
18 0 Open
A/B testing & experimentation medium

How to simulate a contextual bandit in Python

Simulate a contextual multi-armed bandit with random features and epsilon-greedy action selection in Python.

bandit-algorithms simulation epsilon-greedy
Python
import random


class ContextualBandit:
    def __init__(self, n_actions=3, n_features=4):
        self.n_actions = n_actions
        self.n_features = n_features
        self.theta = [random.random() for _ in range(n_actions * n_features)]

    def mock_context(self):
        return [random.uniform(-1, 1) for _ in ra…
13 0 Open
Production deployment patterns medium

How to Build a GitOps Argo CD Sync Mock in Python

Simulate Argo CD-style GitOps deployment sync with Python dataclasses, random success rates, and force-sync retry logic.

gitops argo-cd deployment
Python
import random
import time
from dataclasses import dataclass, field
from typing import List, Dict


@dataclass
class Application:
    name: str
    source_repo: str
    target_revision: str
    synced: bool = False
    health_status: str = "Healthy"
    history: List[Dict] = field(default_factory=list)

    def sync(se…
13 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.