Reference library

Python Code Samples

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

29 matches
Files & data medium

How to Merge Sorted Chunk Files in Python

Merge multiple sorted text files into one sorted output file using a heap for efficient k-way merging.

heapq merge-sort external-sort
Python
import heapq


def merge_sorted_chunks(chunks, output_path):
    """Merge multiple sorted iterables into single sorted output file."""
    with open(output_path, "w") as out_f:
        # Open all chunk files
        handles = [open(chunk, "r") for chunk in chunks]
        try:
            # Heap of (value, index) tupl…
14 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
Algorithms & data structures medium

Find All Triplets with Sum Zero in Python

This code finds all unique triplets in an array that sum to zero using a sorted array and two-pointer technique.

triplets two-pointers sorting
Python
def find_triplets(nums):
    nums.sort()
    n = len(nums)
    triplets = []
    for i in range(n - 2):
        if i > 0 and nums[i] == nums[i - 1]:
            continue
        left, right = i + 1, n - 1
        while left < right:
            total = nums[i] + nums[left] + nums[right]
            if total == 0:
    …
14 0 Open
Algorithms & data structures medium

Find Longest Consecutive Sequence in Python

Find the length of the longest consecutive elements sequence in an unsorted array using a set for O(n) lookups.

set longest-sequence hash-table
Python
def longest_consecutive_length(nums):
    num_set = set(nums)
    longest = 0
    
    for num in num_set:
        if num - 1 not in num_set:
            current = num
            current_streak = 1
            
            while current + 1 in num_set:
                current += 1
                current_streak += 1
…
13 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

How to Find Four Sum Quadruplets in Python (Sorted Demo)

Find all unique quadruplets in a sorted array that sum to a target, with duplicate skipping.

two-pointers sorting four-sum
Python
def four_sum(nums, target):
    nums.sort()
    result = []
    n = len(nums)

    for i in range(n - 3):
        if i > 0 and nums[i] == nums[i - 1]:
            continue
        for j in range(i + 1, n - 2):
            if j > i + 1 and nums[j] == nums[j - 1]:
                continue
            left, right = j + 1…
13 0 Open
Algorithms & data structures medium

How to Find Intersection of Two Sorted Interval Lists in Python

A two-pointer algorithm that finds all overlapping intervals between two sorted lists of intervals.

intervals two-pointers algorithm
Python
def interval_intersection(list1, list2):
    i = j = 0
    result = []
    
    while i < len(list1) and j < len(list2):
        # Find the overlap between current intervals
        lo = max(list1[i][0], list2[j][0])
        hi = min(list1[i][1], list2[j][1])
        
        # If there's an overlap, add it to result
…
13 0 Open
Algorithms & data structures medium

How to Find Minimum Swaps to Sort an Array in Python

Calculate the minimum number of adjacent-free swaps needed to sort a permutation array using cycle detection in Python.

sorting cycles greedy
Python
def min_swaps_to_sort(arr):
    n = len(arr)
    arr_pos = sorted((val, idx) for idx, val in enumerate(arr))
    visited = [False] * n
    swaps = 0

    for i in range(n):
        if visited[i] or arr_pos[i][1] == i:
            continue

        cycle_size = 0
        j = i
        while not visited[j]:
            …
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

Merge k sorted lists in Python using a heap

Merge k individually sorted lists into one sorted list in Python using a min-heap.

heapq merge sorted-list
Python
import heapq

def merge_k_sorted_lists(lists):
    heap = []
    # Push the first element of each list onto the heap
    for i, lst in enumerate(lists):
        if lst:
            heapq.heappush(heap, (lst[0], i, 0))
    
    result = []
    while heap:
        val, list_idx, elem_idx = heapq.heappop(heap)
        re…
15 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
Comprehensions & generators medium

Merge Sorted Iterators with a Heap Generator in Python

Merge multiple sorted iterators into a single sorted stream using a heap and generator, yielding values lazily in order.

heapq generator merge
Python
import heapq

def merge_sorted_iterators(*iterators):
    heap = []
    for idx, iterator in enumerate(iterators):
        try:
            value = next(iterator)
            heapq.heappush(heap, (value, idx, iterator))
        except StopIteration:
            continue

    while heap:
        value, idx, iterator = …
15 0 Open
Automation & scripting medium

Generate Holiday Calendars for Different Countries in Python

Generate a sorted list of public holidays for a given country and year using Python's calendar and datetime modules.

calendar datetime holidays
Python
import calendar
from datetime import date, timedelta

def generate_holiday_calendar(country_code, year=2025):
    holidays = []
    
    if country_code == "US":
        # New Year's Day
        holidays.append(date(year, 1, 1))
        # Independence Day
        holidays.append(date(year, 7, 4))
        # Thanksgivin…
38 0 Open
Automation & scripting medium

How to Build a Python Tool That Finds Trending Open Source Projects Daily

A Python script that queries the GitHub Search API to fetch the top 5 trending repositories created in the last day, sorted by stars, with optional language filtering.

github api trending
Python
import requests
import json
import datetime

def fetch_trending_projects(language: str = "", since: str = "daily"):
    url = "https://api.github.com/search/repositories"
    date_limit = (datetime.date.today() - datetime.timedelta(days=1)).isoformat()
    query = f"created:>{date_limit} language:{language}" if langua…
45 0 Open
Automation & scripting medium

How to apply Kubernetes YAML files from a folder in Python

Uses the Kubernetes Python client to apply all YAML manifests in a directory, with sorted processing and per-file error handling.

kubernetes yaml automation
Python
import os
import yaml
from kubernetes import client, config
from kubernetes.utils import create_from_yaml

def apply_yaml_folder(folder_path):
    """Apply all YAML files in a folder using the Kubernetes mock client."""
    # Load mock configuration
    config.load_kube_config()
    k8s_client = client.ApiClient()

  …
12 0 Open
Data pipelines & processing medium

How to Topologically Sort a DAG in Python

Compute a valid execution order for tasks with dependencies using Kahn's algorithm in Python.

dag topological-sort graph
Python
from collections import defaultdict, deque


def topological_order(dependencies):
    graph = defaultdict(list)
    in_degree = defaultdict(int)
    tasks = set(dependencies.keys())

    for task, depends_on in dependencies.items():
        for d in depends_on:
            graph[d].append(task)
            in_degree[t…
11 0 Open
Data pipelines & processing medium

Implement an Out-of-Order Sort Buffer with a Heap in Python

Buffers out-of-order indices from a stream and emits them in sorted order using a min-heap with a sliding window.

heapq sorting streaming
Python
import heapq
from collections import deque


class OutOfOrderSorter:
    def __init__(self, buffer_size):
        self.buffer_size = buffer_size
        self.buffer = deque(maxlen=buffer_size)
        self.heap = []
        self.next_expected_index = 0
        self.result = []

    def push(self, item):
        heapq.…
12 0 Open
Concurrency & performance medium

Build a Python Performance Profiler That Generates Readable Reports

Use cProfile and pstats to profile Python functions and print a sorted performance report showing the top time-consuming calls.

profiling cprofile pstats
Python
import cProfile
import pstats
import io
from pathlib import Path

def slow_function():
    total = 0
    for i in range(500_000):
        total += i ** 2
    return total

def fast_function():
    total = sum(i * i for i in range(500_000))
    return total

def profile_functions():
    profiler = cProfile.Profile()
  …
44 0 Open
Concurrency & performance medium

How to Profile CPU Hot Path in Python with cProfile and sort_stats cumtime

Profile a Python function's CPU usage by running cProfile, sorting stats by cumulative time, and printing a readable report to stdout.

cprofile profiling performance
Python
import cProfile
import pstats
import io


def slow_function():
    total = 0
    for i in range(100_000):
        total += i * i
    return total


def fast_function():
    return sum(i for i in range(100))


def main():
    slow_function()
    fast_function()


if __name__ == "__main__":
    profiler = cProfile.Profi…
12 0 Open
Concurrency & performance medium

Merge K Sorted Lists in Python with heapq

Merge k sorted lists into one sorted list in O(N log k) time using a min-heap of current elements.

heapq merge sorted-lists
Python
import heapq

def merge_k_sorted_lists(lists):
    heap = []
    for i, lst in enumerate(lists):
        if lst:  # only push non-empty lists
            heapq.heappush(heap, (lst[0], i, 0))
    result = []
    while heap:
        val, list_idx, elem_idx = heapq.heappop(heap)
        result.append(val)
        if elem…
13 0 Open
Testing & modern typing medium

How to Compare Execution Speed Between Python Functions

Measure and compare the average execution time of multiple Python functions using a reusable benchmark helper with time.perf_counter.

performance benchmarking time
Python
import time
import random

def method_a(values):
    """Sort using built-in sorted."""
    return sorted(values)

def method_b(values):
    """Sort using list's sort method."""
    values_copy = values[:]
    values_copy.sort()
    return values_copy

def method_c(values):
    """Sort manually using bubble sort (slow,…
37 0 Open
System design patterns medium

How to Implement the Strategy Pattern in Python

This Python code demonstrates the Strategy design pattern using interchangeable sorting algorithms (bubble sort and quick sort) that can be swapped at runtime.

design-pattern strategy oop
Python
class SortingStrategy:
    def sort(self, data):
        raise NotImplementedError

class BubbleSort(SortingStrategy):
    def sort(self, data):
        result = data.copy()
        n = len(result)
        for i in range(n):
            for j in range(0, n - i - 1):
                if result[j] > result[j + 1]:
      …
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.