Test Algorithms against a Brute-Force Oracle
Core idea
An oracle is a simple independent way to compute the expected answer for small inputs. Compare an optimized algorithm against it over bounded exhaustive inputs, plus explicit edge cases. A mismatch is a counterexample; agreement is evidence, not a proof for all inputs. For subset sums, enumerate every include/exclude mask independently of the state-counting recurrence.
from itertools import productdef oracle(a,target): return sum(sum(x for x,take in zip(a,mask) if take)==target for mask in product((False,True),repeat=len(a)))def fast(a,target): counts={0:1} for x in a: updated=counts.copy() for total,n in counts.items(): updated[total+x]=updated.get(total+x,0)+n counts=updated return counts.get(target,0)print(all(fast(a,t)==oracle(a,t) for a in product(range(3),repeat=3) for t in range(7)))All 189 small pairs agree. Subsets are distinguished by item positions, including repeated zeros.
Expose an edge case
def wrong(a): return max(a,default=0) if a else 0def oracle(a): return max([0]+a)a=[-3,-1]print(wrong(a),oracle(a))For a contract that allows choosing zero instead of a negative maximum, the optimized candidate fails.
Common mistake
An oracle that repeats the same recurrence and bug is weak evidence. Bound exhaustive search because it grows combinatorially, and ensure the oracle and candidate use the same contract.
Practice
Compare the rolling tile-cost solution with explicit enumeration of paths for lengths 1 through 5. Include zeros, ties and a one-tile input.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Algorithm test design
Check your understanding of algorithm test design.
What is printed?
from itertools import productprint(len(list(product(range(3),repeat=2))))What is printed?
print(max([0,-3,-1]))What does one mismatch establish?
Why keep an oracle independent?