Reference library

Python Code Samples

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

86 matches
Strings & text medium

Convert Natural Language Dates to Datetime in Python

Parse common natural language date phrases like 'tomorrow' or 'in 3 days' into Python datetime objects using regex and timedelta.

datetime natural-language regex
Python
from datetime import datetime, timedelta
import re

def parse_natural_date(text: str) -> datetime:
    """Convert common natural language date expressions to datetime objects."""
    now = datetime.now()
    text = text.lower().strip()
    
    # Handle relative dates
    patterns = {
        r"today": now,
        r"…
61 0 Open
Errors & debugging medium

How to Simulate Timeout with Custom TimeoutError in Python

Run a function in a daemon thread and raise a custom TimeoutError if it exceeds a specified time limit.

timeout threading exceptions
Python
import time
from typing import Callable, TypeVar

T = TypeVar("T")


class TimeoutError(Exception):
    """Raised when an operation exceeds its time limit."""

    def __init__(self, message: str = "Operation timed out"):
        self.message = message
        super().__init__(self.message)


def run_with_timeout(func…
12 0 Open
Errors & debugging medium

Implement circuit breaker open after failures demo in Python

A minimal CircuitBreaker class that calls a function and automatically 'opens' after a set number of consecutive failures, blocking further calls with a RuntimeError.

circuit-breaker resilience error-handling
Python
import time
from datetime import datetime


class CircuitBreaker:
    def __init__(self, threshold=3):
        self.threshold = threshold
        self.failure_count = 0
        self.is_open = False

    def call(self, func, *args, **kwargs):
        if self.is_open:
            raise RuntimeError("Circuit is OPEN")
  …
12 0 Open
Files & data medium

Build a Personal Work Hours Tracker in Python

A Python class that logs daily work hours to a CSV file and produces a weekly summary of total hours worked.

work-hours time-tracking csv
Python
import csv
from pathlib import Path
from datetime import datetime, date

class WorkHoursTracker:
    def __init__(self, file_path="work_hours.csv"):
        self.file_path = Path(file_path)
        if not self.file_path.exists():
            with open(self.file_path, "w", newline="") as f:
                writer = csv…
60 0 Open
Files & data medium

Calculate Working Hours Between Two Dates in Python

Compute total business hours (Mon-Fri, 09:00-17:00) between two datetime objects, excluding weekends and non-working hours.

datetime working hours business hours
Python
from datetime import datetime, timedelta

def work_hours_between(start: datetime, end: datetime) -> float:
    """Calculate total working hours between two datetimes (Mon-Fri, 09:00-17:00)."""
    def is_workday(d: datetime) -> bool:
        return d.weekday() < 5
    
    total_hours = 0.0
    current = start
    whi…
48 0 Open
Dictionaries & sets medium

How to Build a TTL Cache Dict in Python

Create a dictionary subclass that automatically expires keys after a fixed time-to-live using timestamps.

dictionary cache ttl
Python
import time

class TTLDict(dict):
    def __init__(self, ttl, *args, **kwargs):
        self.ttl = ttl
        self._expires = {}
        super().__init__(*args, **kwargs)

    def __setitem__(self, key, value):
        super().__setitem__(key, value)
        self._expires[key] = time.time() + self.ttl

    def __geti…
16 0 Open
OOP & classes medium

Implement the Strategy Pattern with Interchangeable Algorithm Classes in Python

Uses abstract base classes to define a SortStrategy interface, then swaps between BubbleSort and QuickSort at runtime.

strategy-pattern oop abstract-class
Python
from abc import ABC, abstractmethod
from typing import List


class SortStrategy(ABC):
    @abstractmethod
    def sort(self, data: List[int]) -> List[int]:
        pass


class BubbleSort(SortStrategy):
    def sort(self, data: List[int]) -> List[int]:
        result = data[:]
        n = len(result)
        for i in…
12 0 Open
OOP & classes medium

Visitor Pattern in Python: Double Dispatch Demo

Demonstrates the Visitor design pattern with double dispatch so operations on Dog and Cat objects are selected at runtime without modifying their classes.

visitor-pattern design-patterns double-dispatch
Python
class Animal:
    def accept(self, visitor):
        visitor.visit(self)

class Dog(Animal):
    def speak(self):
        return "Woof!"

class Cat(Animal):
    def speak(self):
        return "Meow!"

class SoundVisitor:
    def visit(self, animal):
        if isinstance(animal, Dog):
            return self.visit_do…
11 0 Open
Algorithms & data structures medium

Container With Most Water: Two-Pointer Solution in Python

Find the maximum water a container can hold from a list of heights using an efficient two-pointer technique in O(n) time.

two-pointer array algorithm
Python
from typing import List

def max_water_container(heights: List[int]) -> int:
    left, right = 0, len(heights) - 1
    max_area = 0
    
    while left < right:
        width = right - left
        height = min(heights[left], heights[right])
        area = width * height
        max_area = max(max_area, area)
        …
15 0 Open
Algorithms & data structures medium

Find Minimum in Rotated Sorted List in Python

Uses binary search to find the minimum element in a rotated sorted list in O(log n) time.

binary-search minimum rotated-array
Python
def find_min(nums):
    left, right = 0, len(nums) - 1
    while left < right:
        mid = (left + right) // 2
        if nums[mid] > nums[right]:
            left = mid + 1
        else:
            right = mid
    return nums[left]


if __name__ == "__main__":
    rotated = [4, 5, 6, 7, 0, 1, 2]
    print(f"Minimu…
12 0 Open
Algorithms & data structures medium

Find Peak Element in Python Using Binary Search

A binary search solution that finds any peak element (an element strictly greater than its neighbors) in an unsorted array in O(log n) time.

binary-search peak array
Python
def find_peak_element(nums):
    left, right = 0, len(nums) - 1
    
    while left < right:
        mid = (left + right) // 2
        if nums[mid] > nums[mid + 1]:
            right = mid
        else:
            left = mid + 1
            
    return left

if __name__ == "__main__":
    test1 = [1, 2, 3, 1]
    tes…
17 0 Open
Algorithms & data structures medium

Find the Duplicate Number in Python Using Floyd's Cycle Detection

Detects the duplicate integer in an array of n+1 numbers (values 1 to n) in O(n) time and O(1) space using Floyd's cycle detection algorithm applied to a linked-list model.

floyd-cycle duplicate-number two-pointers
Python
def find_duplicate(nums):
    slow = nums[0]
    fast = nums[0]
    
    # Phase 1: Find intersection point of the cycle
    while True:
        slow = nums[slow]
        fast = nums[nums[fast]]
        if slow == fast:
            break
    
    # Phase 2: Find the start of the cycle (the duplicate)
    slow = nums[0…
14 0 Open
Algorithms & data structures medium

Find the Majority Element in Python with Boyer-Moore Vote

Use Boyer-Moore majority vote to find the element appearing more than n/2 times in an array in O(n) time and O(1) space.

boyer-moore majority-element array
Python
def majority_element(nums):
    candidate = None
    count = 0

    for num in nums:
        if count == 0:
            candidate = num
        count += 1 if num == candidate else -1

    return candidate

if __name__ == "__main__":
    nums = [2, 2, 1, 1, 1, 2, 2]
    result = majority_element(nums)
    print(f"Major…
14 0 Open
Algorithms & data structures medium

Find two unique numbers in an array with Python

Returns the two numbers that appear exactly once in a list where every other number appears twice, using XOR bit manipulation.

bit-manipulation xor arrays
Python
def find_two_odd(arr):
    """Return the two numbers that appear exactly once, while all others appear twice."""
    xor_all = 0
    for num in arr:
        xor_all ^= num

    # xor_all now equals the XOR of the two unique numbers.
    # Find a set bit (any bit where they differ).
    diff_bit = xor_all & (-xor_all)
…
13 0 Open
Algorithms & data structures medium

How to Find the Next Greater Element for Each List Item in Python

Use a monotonic stack to find the next greater element to the right for every item in a list, in O(n) time.

stack monotonic stack algorithm
Python
def next_greater_element(nums):
    result = [-1] * len(nums)
    stack = []
    
    for i in range(len(nums) - 1, -1, -1):
        while stack and stack[-1] <= nums[i]:
            stack.pop()
        result[i] = stack[-1] if stack else -1
        stack.append(nums[i])
    
    return result


if __name__ == "__main…
13 0 Open
Algorithms & data structures medium

How to Search a Rotated Sorted List in Python

Binary search a pivot-rotated sorted list for a target value and return its index in O(log n) time.

binary-search rotated-array search-algorithm
Python
from typing import List

def search_rotated(nums: List[int], target: int) -> int:
    left, right = 0, len(nums) - 1

    while left <= right:
        mid = (left + right) // 2
        if nums[mid] == target:
            return mid

        # left half is sorted
        if nums[left] <= nums[mid]:
            if nums[…
12 0 Open
Algorithms & data structures medium

How to Sort Colors (Dutch National Flag) in Python

In-place sorting of a list of 0s, 1s, and 2s using the Dutch National Flag algorithm with O(n) time and O(1) space.

algorithm sorting two-pointers
Python
def sort_colors(nums):
    low, mid, high = 0, 0, len(nums) - 1

    while mid <= high:
        if nums[mid] == 0:
            nums[low], nums[mid] = nums[mid], nums[low]
            low += 1
            mid += 1
        elif nums[mid] == 1:
            mid += 1
        else:  # nums[mid] == 2
            nums[mid], n…
14 0 Open
Algorithms & data structures medium

How to solve the stock span problem in Python

Calculate the stock span for each day's price using a monotonic stack in O(n) time.

stack monotonic-stack algorithm
Python
def stock_span(prices):
    span = [1] * len(prices)
    stack = []
    
    for i in range(len(prices)):
        while stack and prices[stack[-1]] <= prices[i]:
            stack.pop()
        span[i] = i - stack[-1] if stack else i + 1
        stack.append(i)
    
    return span

if __name__ == "__main__":
    pric…
13 0 Open
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
Algorithms & data structures medium

Product of All Elements Except Self in Python

Given a list of integers, return a list where each element is the product of all other elements except itself, using prefix and suffix products in O(n) time and O(1) extra space.

array prefix suffix
Python
def product_except_self(nums):
    n = len(nums)
    result = [1] * n
    
    left_product = 1
    for i in range(n):
        result[i] = left_product
        left_product *= nums[i]
    
    right_product = 1
    for i in range(n - 1, -1, -1):
        result[i] *= right_product
        right_product *= nums[i]
    
…
14 0 Open
Algorithms & data structures medium

Product of Array Except Self in Python Without Division

Compute the product of all array elements except the current one in O(n) time using prefix and suffix products, without using division.

arrays prefix-product suffix-product
Python
from math import prod


def product_except_self(nums):
    n = len(nums)
    result = [1] * n
    left_product = 1
    for i in range(n):
        result[i] = left_product
        left_product *= nums[i]

    right_product = 1
    for i in range(n - 1, -1, -1):
        result[i] *= right_product
        right_product *…
14 0 Open
Algorithms & data structures medium

Quickselect in Python: Find the kth Smallest Element

Python implementation of the Quickselect algorithm to find the kth smallest element in an unsorted list with average O(n) time complexity.

quickselect selection algorithm
Python
def quickselect(arr, k):
    """
    Returns the k-th smallest element (0-indexed) using Quickselect.
    Average: O(n), Worst: O(n^2)
    """
    if len(arr) == 1:
        return arr[0]

    pivot = arr[-1]
    left = [x for x in arr[:-1] if x <= pivot]
    right = [x for x in arr[:-1] if x > pivot]

    if k < len(l…
16 0 Open
AI & LLM integration patterns medium

Circuit Breaker Pattern in Python for LLM API Calls

Implements a circuit breaker class that wraps LLM client calls to fail fast when the service is degrading, then recover automatically after a timeout.

circuit-breaker llm resilience
Python
import time

class CircuitBreaker:
    def __init__(self, failure_threshold=3, recovery_timeout=5):
        self.failure_threshold = failure_threshold
        self.recovery_timeout = recovery_timeout
        self.failure_count = 0
        self.state = "closed"
        self.last_failure_time = None

    def call(self, …
14 0 Open
Automation & scripting medium

Build a Network Ping Monitor in Python

A Python script that continuously pings a remote host using subprocess and reports connectivity status with timestamps and latency.

ping network monitoring
Python
import subprocess
import time

def ping_host(host, count=4):
    """Ping a host and return the results."""
    try:
        # Platform-independent ping command
        cmd = ["ping", "-c", str(count), host]
        result = subprocess.run(cmd, capture_output=True, text=True, timeout=10)
        return result.stdout, r…
93 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.