Algorithms & data structures
Classic patterns — search, sort, stacks, queues, and practical complexity-aware code.
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.
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…
How to Generate an Arithmetic Progression List in Python
Generates a list of terms in an arithmetic progression using a list comprehension.
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)
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.