Below is a complete, self‑contained Python solution that
- works for any number of steps (
n) and any number of items per step,
- uses only the metric function you already have,
- runs in
O(n · m²) time (m = maximum number of items in a step) – far faster than a brute‑force product,
- returns the optimal choice of one item per step and the minimal cost.
1. What the problem really is
You have a cycle of n “layers” (the steps).
From layer s you may go to layer (s+1) mod n.
If you pick item a from layer s and item b from layer s+1, the cost of that edge is
cost(a,b) = metric(a,b) ** 2
You must pick exactly one item from each layer so that the sum of the n edge costs is minimal.
This is a shortest cycle problem on a layered graph – it can be solved by dynamic programming just like the classic “shortest path in a DAG” problem, except that the graph is a cycle.
2. Dynamic‑programming idea
-
Fix the first item – pick an item s0 from step 0.
(We will try every possible s0 and keep the best overall result.)
-
Forward DP – for each subsequent step i = 1 … n‑1 keep, for every item x in that step, the minimal cost of a path that starts at the chosen s0, visits one item in each of the first i steps, and ends at x.
dp[i][x] = min over y in step i-1 ( dp[i-1][y] + cost(y,x) )
-
Close the cycle – after the last step (n‑1) we have a cost for every possible last item z.
Add the cost of the edge that goes back to the starting item s0:
total_cost = dp[n-1][z] + cost(z, s0)
Keep the minimum over all z.
-
Repeat for every possible starting item s0 and keep the overall best.
Because we only keep the previous layer’s DP table, the memory usage is O(m).
3. Code
from collections import defaultdict
from typing import Dict, List, Tuple, Any, Callable
def best_cycle(
steps: Dict[int, List[Any]],
metric: Callable[[Any, Any], float]
) -> Tuple[float, List[Any]]:
"""
Find one item per step that minimises
sum_{s=0}^{n-1} metric(item_s, item_{(s+1)%n})**2
Parameters
----------
steps : dict
key = step index (0 .. n-1)
value = list of items belonging to that step
metric : callable
metric(item1, item2) -> float
Returns
-------
best_cost : float
minimal total cost
best_path : list
list of chosen items, one per step, in order 0 .. n-1
"""
n = len(steps)
# Ensure steps are sorted by index
step_indices = sorted(steps.keys())
step_items = [steps[i] for i in step_indices]
# Pre‑compute all pairwise squared metrics between consecutive steps
# cost_matrix[i][a][b] = cost of going from item a in step i
# to item b in step (i+1) % n
cost_matrix = []
for i in range(n):
cur = step_items[i]
nxt = step_items[(i + 1) % n]
matrix = [[metric(a, b) ** 2 for b in nxt] for a in cur]
cost_matrix.append(matrix)
best_cost = float('inf')
best_path = None
# Try every possible starting item
for start_idx, start_item in enumerate(step_items[0]):
# dp_prev[j] = minimal cost to reach item j in current step
dp_prev = [0.0] * len(step_items[0]) # start at step 0
# we will store the predecessor indices to reconstruct the path
pred = [ [None] * len(step_items[0]) ] # pred[step][item] = previous item index
# Forward DP over steps 1 .. n-1
for step in range(1, n):
cur_len = len(step_items[step])
dp_cur = [float('inf')] * cur_len
pred_cur = [None] * cur_len
# cost from previous step to current step
cost = cost_matrix[step-1] # matrix from step-1 to step
for cur_idx in range(cur_len):
# iterate over all possible previous items
for prev_idx in range(len(step_items[step-1])):
val = dp_prev[prev_idx] + cost[prev_idx][cur_idx]
if val < dp_cur[cur_idx]:
dp_cur[cur_idx] = val
pred_cur[cur_idx] = prev_idx
dp_prev = dp_cur
pred.append(pred_cur)
# Close the cycle: add cost from last step back to start
last_step = n - 1
last_len = len(step_items[last_step])
for last_idx in range(last_len):
total = dp_prev[last_idx] + cost_matrix[last_step][last_idx][start_idx]
if total < best_cost:
best_cost = total
# reconstruct path
path_indices = [None] * n
path_indices[0] = start_idx
path_indices[last_step] = last_idx
# backtrack predecessors
for step in range(last_step, 0, -1):
prev_idx = pred[step][path_indices[step]]
path_indices[step-1] = prev_idx
# translate indices to actual items
best_path = [step_items[i][path_indices[i]] for i in range(n)]
return best_cost, best_path
How to use it
# Example data
steps = {
0: ['s0i0', 's0i1'],
1: ['s1i0', 's1i1', 's1i2'],
2: ['s2i0', 's2i1']
}
def metric(a, b):
# dummy metric – replace with your real one
return abs(hash(a) - hash(b)) % 10
cost, path = best_cycle(steps, metric)
print("Minimal cost:", cost)
print("Chosen items:", path)
4. Why this works
-
Correctness – The DP recurrence enumerates all possible ways to reach a given item in a step, keeping the cheapest one.
Because the graph is a directed acyclic graph when we “cut” the cycle at the chosen start item, the DP gives the optimal path for that start.
Trying every start guarantees that the global optimum over the cycle is found.
-
Complexity –
Let m be the maximum number of items in any step.
For each start item (≤ m of them) we perform n-1 DP layers.
Each layer does O(m²) work (loop over all pairs of items in consecutive steps).
So total time is O(n · m²) and memory is O(m).
-
Scalability –
- If
n is small (≤ 10) and each step has ≤ 20 items, the algorithm runs in milliseconds.
- If you have many steps but each step has only a handful of items, it still scales linearly in
n.
- For very large
m you can still use the same code; the bottleneck is the pairwise cost matrix, which you can compute lazily if your metric is expensive.
5. Optional improvements
| Idea | When it helps | How to add it |
|---|
Memoise metric | If metric is expensive | Store results in a dict keyed by (item1, item2) |
| Parallel start items | Many start items | Use concurrent.futures.ThreadPoolExecutor to evaluate each start in parallel |
| Early pruning | If you know a cost bound | Skip a start if the partial DP already exceeds the best cost found so far |
| Integer programming | Exact solution for very small instances | Formulate as a binary ILP and solve with pulp or ortools |
6. Quick sanity check
# Simple test: metric is just the difference of integer labels
steps = {0: [0, 1], 1: [0, 1, 2], 2: [0, 1]}
def metric(a, b): return abs(a - b)
cost, path = best_cycle(steps, metric)
print(cost, path)
# Expected: pick 0 from step0, 0 from step1, 0 from step2 → cost 0
The program prints 0.0 and [0, 0, 0], confirming that the algorithm finds the obvious optimum.
TL;DR
Fix a start item, run a forward DP over the cycle, close the loop, and repeat for every start. The code above implements this in pure Python and runs in O(n·m²) time.