Reference library

Algorithms & data structures

Classic patterns — search, sort, stacks, queues, and practical complexity-aware code.

36 matches
Algorithms & data structures easy

Bucket Numbers into Histogram Bin Counts in Python

Partition a list of numbers into equal-width histogram bins and count how many fall into each bin using only the Python standard library.

histogram bins statistics
Python
from collections import Counter

def histogram_bins(numbers, num_bins):
    """Bucket numbers into histogram bin counts."""
    if not numbers:
        return []
    
    min_val = min(numbers)
    max_val = max(numbers)
    bin_width = (max_val - min_val) / num_bins
    
    # Handle edge case where all values are id…
17 0 Open
Algorithms & data structures easy

Count Smaller Elements to the Right in Python

Return a list where each index counts how many elements to its right are smaller than that element using a clean O(n²) nested-loop approach.

brute-force nested-loops counting
Python
def count_smaller_elements(arr):
    """
    Return a list where result[i] is the number of elements 
    to the right of arr[i] that are smaller than arr[i].
    """
    result = []
    for i in range(len(arr)):
        count = 0
        for j in range(i + 1, len(arr)):
            if arr[j] < arr[i]:
               …
14 0 Open
Algorithms & data structures easy

How to Add Two Lists Elementwise in Python

Add two equal-length lists element by element using a list comprehension with zip, returning a new list of summed values.

list zip list-comprehension
Python
def elementwise_add(list1, list2):
    return [a + b for a, b in zip(list1, list2)]

if __name__ == "__main__":
    list_a = [1, 2, 3, 4]
    list_b = [10, 20, 30, 40]
    result = elementwise_add(list_a, list_b)
    print(result)
12 0 Open
Algorithms & data structures easy

How to Apply a Function to Sliding Window Slices in Python

This Python code applies a given function to every contiguous window of a specified size in a list, returning a list of results.

sliding-window list-comprehension algorithms
Python
def apply_to_sliding_windows(data, window_size, func):
    return [func(data[i:i + window_size]) for i in range(len(data) - window_size + 1)]

if __name__ == "__main__":
    numbers = [1, 2, 3, 4, 5, 6]
    window_size = 3
    results = apply_to_sliding_windows(numbers, window_size, sum)
    print(results)
    results…
16 0 Open
Algorithms & data structures easy

How to Build a Coordinate Grid with Nested Loops in Python

Generate a 2D list of (row, col) coordinate pairs using nested loops and return the grid structure.

coordinate grid nested loops 2d list
Python
def build_coordinate_grid(rows, cols):
    """Build a 2D grid of (row, col) coordinates using nested loops."""
    grid = []
    for r in range(rows):
        row = []
        for c in range(cols):
            row.append((r, c))
        grid.append(row)
    return grid


if __name__ == "__main__":
    grid = build_coo…
15 0 Open
Algorithms & data structures easy

How to Combine filter and map with a List Comprehension in Python

This Python code demonstrates how to combine filtering and mapping in a single list comprehension and shows the equivalent filter() and map() approach.

list-comprehension filter map
Python
def square(x):
    return x * x

def is_even(x):
    return x % 2 == 0

numbers = [1, 2, 3, 4, 5, 6, 7, 8]

result = [square(x) for x in numbers if is_even(x)]

print(f"Original numbers: {numbers}")
print(f"Squares of even numbers: {result}")

# Combined filter + map equivalent
filtered = filter(is_even, numbers)
mapp…
13 0 Open
Algorithms & data structures easy

How to Compare Two Lists Elementwise for Greater Flags in Python

Compare two equal-length lists element by element and return a list of booleans marking where list_a values are greater than list_b values.

lists comparison zip
Python
def compare_lists_greater(list_a, list_b):
    """
    Compare two lists elementwise and return a list of booleans
    indicating whether each element in list_a is greater than the
    corresponding element in list_b.
    """
    if len(list_a) != len(list_b):
        raise ValueError("Lists must have the same length"…
13 0 Open
Algorithms & data structures easy

How to Compute Cosine Similarity Between Two Vectors in Python

This code calculates the cosine similarity between two numeric vectors using the dot product and Euclidean norms, returning a value between -1 and 1.

cosine similarity vectors math
Python
import math

def cosine_similarity(vec_a, vec_b):
    if len(vec_a) != len(vec_b):
        raise ValueError("Vectors must have the same length")
    
    dot_product = sum(a * b for a, b in zip(vec_a, vec_b))
    norm_a = math.sqrt(sum(a * a for a in vec_a))
    norm_b = math.sqrt(sum(b * b for b in vec_b))
    
    i…
14 0 Open
Algorithms & data structures easy

How to Compute Jaccard Similarity in Python

Compute the Jaccard similarity between two lists by converting them to sets and dividing the intersection size by the union size.

jaccard sets similarity
Python
def jaccard_similarity(list1, list2):
    set1 = set(list1)
    set2 = set(list2)
    
    intersection = set1 & set2
    union = set1 | set2
    
    if not union:
        return 0.0
    
    return len(intersection) / len(union)

if __name__ == "__main__":
    a = [1, 2, 3, 4, 5]
    b = [3, 4, 5, 6, 7]
    
    pri…
17 0 Open
Algorithms & data structures easy

How to Compute the Cartesian Product of Two Lists in Python

Generates all ordered pairs from two lists using itertools.product and prints each combination.

itertools cartesian-product combinations
Python
from itertools import product

# Two small input lists
list_a = [1, 2, 3]
list_b = ["x", "y"]

# Compute the Cartesian product
result = list(product(list_a, list_b))

# Display the result
print("Cartesian product of", list_a, "and", list_b, "is:")
for pair in result:
    print(pair)
15 0 Open
Algorithms & data structures easy

How to Compute the Dot Product of Two Lists in Python

Compute the dot product of two equal-length numeric lists using a generator expression with zip and sum.

dot product zip sum
Python
def dot_product(list1, list2):
    """
    Compute the dot product of two numeric lists.
    The lists must have the same length.
    """
    if len(list1) != len(list2):
        raise ValueError("Lists must have the same length")
    
    return sum(a * b for a, b in zip(list1, list2))


if __name__ == "__main__":
  …
13 0 Open
Algorithms & data structures easy

How to Count Distinct Elements in a List in Python

Count the number of unique items in a list by converting it to a set and returning its length.

set count unique
Python
def count_distinct_elements(items):
    return len(set(items))

if __name__ == "__main__":
    sample = [1, 2, 3, 2, 1, 4, 3, 5, 4, 6]
    result = count_distinct_elements(sample)
    print(result)
14 0 Open
Algorithms & data structures easy

How to Count Occurrences of Each Value in Python

Count how many times each value appears in a list using Python's Counter from the collections module.

counter counting collections
Python
from collections import Counter

def count_occurrences(values):
    """Return a dictionary mapping each value to its count."""
    return dict(Counter(values))

if __name__ == "__main__":
    sample_data = ["apple", "banana", "apple", "cherry", "banana", "apple"]
    result = count_occurrences(sample_data)
    print(r…
10 0 Open
Algorithms & data structures easy

How to Find Gaps Between Sorted Intervals in Python

This code finds gap ranges between sorted intervals using pairwise iteration, returning ranges where no interval covers.

intervals pairwise sorting
Python
from itertools import pairwise

def find_gaps(intervals):
    intervals = sorted(intervals)
    gaps = []
    for prev, curr in pairwise(intervals):
        if prev[1] < curr[0]:
            gaps.append((prev[1] + 1, curr[0] - 1))
    return gaps

if __name__ == "__main__":
    intervals = [(1, 3), (5, 7), (10, 12), (…
14 0 Open
Algorithms & data structures easy

How to Find the Nearest Value to a Target in a Sorted List in Python

Use bisect to binary-search a sorted list and return the element closest to a target value.

bisect binary-search sorted-list
Python
import bisect

def nearest_value(sorted_list, target):
    if not sorted_list:
        return None
    pos = bisect.bisect_left(sorted_list, target)
    if pos == 0:
        return sorted_list[0]
    if pos == len(sorted_list):
        return sorted_list[-1]
    before = sorted_list[pos - 1]
    after = sorted_list[po…
15 0 Open
Algorithms & data structures easy

How to Flatten List of Dict Values in Python

This code flattens the values of a list of dictionaries into a single list, handling both list values and scalar values.

flatten dictionaries lists
Python
def flatten_dict_values(dicts):
    flattened = []
    for d in dicts:
        for value in d.values():
            if isinstance(value, list):
                flattened.extend(value)
            else:
                flattened.append(value)
    return flattened


if __name__ == "__main__":
    data = [
        {"a": …
12 0 Open
Algorithms & data structures easy

How to Generate Fibonacci Sequence in Python

Generate the first n Fibonacci numbers as a list using a simple iterative loop.

fibonacci sequences iteration
Python
def fibonacci(n):
    """Generate the first n terms of the Fibonacci sequence."""
    if n <= 0:
        return []
    seq = [0, 1]
    while len(seq) < n:
        seq.append(seq[-1] + seq[-2])
    return seq[:n]

if __name__ == "__main__":
    n = 10
    result = fibonacci(n)
    print(result)
13 0 Open
Algorithms & data structures easy

How to Generate Permutations of Length r in Python

Generate and print all r-length permutations of a list using Python's itertools.permutations.

permutations itertools combinations
Python
from itertools import permutations

def show_permutations(items, r):
    result = list(permutations(items, r))
    for perm in result:
        print(perm)
    print(f"Total: {len(result)}")

if __name__ == "__main__":
    data = ["A", "B", "C"]
    show_permutations(data, 2)
15 0 Open
Algorithms & data structures easy

How to Generate a Geometric Progression List in Python

This Python function builds a list of n terms in a geometric progression, starting with a given first term and multiplying by a constant ratio at each step.

geometric-progression sequence algorithms
Python
def geometric_progression(first_term, ratio, count):
    """
    Generate a list of 'count' terms in a geometric progression
    starting with 'first_term' and multiplied by 'ratio' each step.
    """
    progression = []
    current = first_term
    for _ in range(count):
        progression.append(current)
        c…
13 0 Open
Algorithms & data structures easy

How to Generate an Arithmetic Progression List in Python

Generates a list of terms in an arithmetic progression using a list comprehension.

arithmetic list-comprehension sequences
Python
def generate_ap(start, difference, count):
    """Generate a list of n terms in an arithmetic progression."""
    return [start + i * difference for i in range(count)]


if __name__ == "__main__":
    ap = generate_ap(3, 5, 6)
    print(ap)
14 0 Open
Algorithms & data structures easy

How to Get All Combinations of a List in Python

Generate and display all combinations of a given length from a list using Python's itertools.combinations.

itertools combinations list
Python
from itertools import combinations

def list_combinations(items, r):
    """Return all combinations of length r from a list."""
    return list(combinations(items, r))

if __name__ == "__main__":
    fruits = ["apple", "banana", "cherry", "date"]
    pick = 2
    result = list_combinations(fruits, pick)
    
    print…
12 0 Open
Algorithms & data structures easy

How to Get the Breadth-First Traversal Order of a Graph in Python

Performs a breadth-first search on an adjacency list and returns the order nodes are visited, using a deque for efficient queue operations.

graph bfs queue
Python
from collections import deque

def bfs_order(adjacency, start=0):
    """Return the order nodes are visited in a breadth-first traversal."""
    visited = set()
    order = []
    queue = deque([start])
    visited.add(start)

    while queue:
        node = queue.popleft()
        order.append(node)

        for neig…
14 0 Open
Algorithms & data structures easy

How to Heapify a List into a Min Heap with heapq in Python

Convert any list into a valid min heap in-place using Python's heapq.heapify(), then pop the smallest element to verify heap order.

heapq min heap heapify
Python
import heapq

data = [5, 3, 8, 1, 9, 2, 7, 4, 6]
print("Original list:", data)

heapq.heapify(data)
print("Min heap:", data)

popped = heapq.heappop(data)
print("Smallest element popped:", popped)
print("Heap after pop:", data)
14 0 Open
Algorithms & data structures easy

How to Implement a Moving Average from a Data Stream in Python

Implement a MovingAverage class using a deque and running sum to compute the average of the last k values from a continuous data stream.

deque sliding-window streaming
Python
from collections import deque

class MovingAverage:
    def __init__(self, size):
        self.size = size
        self.queue = deque()
        self.window_sum = 0

    def next(self, val):
        self.queue.append(val)
        self.window_sum += val

        if len(self.queue) > self.size:
            self.window_su…
12 0 Open

Browse by section

Each section groups closely related Python snippets.

Algorithms & data structures — Python code examples

What you will find here

This page collects algorithms & data structures snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.

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.