Reference library

Algorithms & data structures

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

3 matches
Algorithms & data structures medium

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.

binary-search algorithms search
Python
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…
15 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 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

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.