Python Code
Samples
Medium snippets you can copy, study, and run in the browser editor.
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.
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…
Binary Search on Answer in Python: Koko Eating Bananas
Find the minimum eating speed so Koko finishes all banana piles within a given hour limit using binary search on the answer.
import math
def min_eating_speed(piles, h):
"""Return minimum integer eating speed K so Koko finishes within h hours."""
def hours_needed(speed):
return sum(math.ceil(p / speed) for p in piles)
low, high = 1, max(piles)
while low < high:
mid = (low + high) // 2
if hours_needed…
Find Missing Numbers, Duplicates, and Ranges in Python
Analyze a list to identify missing numbers, duplicate values, and contiguous ranges using sets and the Counter class.
def find_missing_duplicates_ranges(numbers):
"""Find missing numbers, duplicates, and ranges in a list."""
from collections import Counter
if not numbers:
return {"missing": [], "duplicates": [], "ranges": []}
full_range = set(range(min(numbers), max(numbers) + 1))
present = set(n…
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.
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…
Game of Life Next State Grid in Python
Compute the next generation of Conway's Game of Life from a 2D grid using the standard three rules with neighbor counting.
def next_state(grid):
m, n = len(grid), len(grid[0])
new = [[0] * n for _ in range(m)]
for r in range(m):
for c in range(n):
total = 0
for dr in (-1, 0, 1):
for dc in (-1, 0, 1):
if dr == 0 and dc == 0:
continue
…
How to Decode a String with Repeated Brackets in Python
Decodes strings with patterns like '3[a]2[bc]' by using a stack to handle nested and repeated bracket groups.
def decode_string(s: str) -> str:
stack = []
current_num = 0
current_str = ""
for ch in s:
if ch.isdigit():
current_num = current_num * 10 + int(ch)
elif ch == "[":
stack.append((current_str, current_num))
current_str = ""
current_num = 0…
How to Evaluate RPN Expressions in Python
Use a stack to evaluate Reverse Polish Notation token lists with a dictionary of operator lambdas, truncating division toward zero.
def eval_rpn(tokens):
stack = []
ops = {
'+': lambda a, b: a + b,
'-': lambda a, b: a - b,
'*': lambda a, b: a * b,
'/': lambda a, b: int(a / b) # truncate toward zero
}
for token in tokens:
if token in ops:
b = stack.pop()
a = stack.pop(…
How to Generate a Power Set in Python with Bitmasks
Generate the power set of a small list using a bitmask approach, producing all possible subsets.
def power_set(items):
"""Generate the power set of a list using bitmask approach."""
n = len(items)
result = []
for mask in range(1 << n):
subset = []
for i in range(n):
if mask & (1 << i):
subset.append(items[i])
result.append(subset)
r…
How to Solve the Trapping Rain Water Problem in Python
Compute the total water trapped between elevation bars using a two-pointer O(n) algorithm.
def trap(height):
if not height:
return 0
left, right = 0, len(height) - 1
left_max, right_max = 0, 0
water = 0
while left < right:
if height[left] < height[right]:
if height[left] >= left_max:
left_max = height[left]
else:
…
Validate Sudoku Board Rows Columns and Boxes in Python
Validate a 9x9 Sudoku board by checking that each row, column, and 3x3 box contains the numbers 1 through 9 exactly once.
def validate_sudoku(board):
def is_valid_group(group):
return sorted(group) == list(range(1, 10))
def get_columns():
return [[board[r][c] for r in range(9)] for c in range(9)]
def get_boxes():
boxes = []
for box_row in range(0, 9, 3):
for box_col in range(0, 9,…
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.
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…
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.
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]:
…
Redis Leaky Bucket Rate Limiting Mock in Python
Simulates a Redis-backed leaky bucket rate limiter using a local class with continuous leaking and token capacity checks.
import time
from collections import deque
class LeakyBucket:
def __init__(self, capacity, leak_rate):
self.capacity = capacity
self.leak_rate = leak_rate
self.water = 0.0
self.timestamp = time.time()
self.history = deque()
def allow(self):
current = time.time(…
How to Build a DAG Execution Stage Calculator in Python
Computes the execution stages of a directed acyclic graph (DAG) by grouping nodes that become ready simultaneously using topological sorting with Kahn's algorithm.
from collections import defaultdict, deque
def get_stages(edges):
"""Return list of stages, where each stage is a list of nodes
that become ready at the same time in a DAG."""
graph = defaultdict(list)
in_degree = defaultdict(int)
nodes = set()
for src, dst in edges:
graph[src].appen…
How to simulate a contextual bandit in Python
Simulate a contextual multi-armed bandit with random features and epsilon-greedy action selection in 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…
Thompson Sampling Mock Bandit in Python
Implement a Thompson sampling multi-armed bandit to explore and exploit reward probabilities across multiple options, updating Beta distributions over time.
import random
class ThompsonSamplingBandit:
def __init__(self, num_arms, alpha=1.0, beta=1.0):
self.num_arms = num_arms
self.alpha = [alpha] * num_arms
self.beta = [beta] * num_arms
def select_arm(self):
samples = [random.betavariate(a, b) for a, b in zip(self.alpha, self.beta…
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
- Pick a topic section — strings, lists, files, functions, and more
- Open a sample, read How it works, and copy the code block
- 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.