Sub topic 9
Using Brute Force to Test Faster Code
This chapter assumes you can write Python functions and loops, know how a dictionary works, and have the two-sum solutions from earlier chapters in mind. The brute-force version checks every pair. The fast version remembers earlier values in a dictionary.
An optimized solution is harder to trust than a brute-force one. It has more moving parts, and each part can hide a bug that only shows up on unusual inputs. The brute-force solution you already wrote is slow, but you can check its correctness by reading it. That makes it useful as an oracle: a reference implementation whose answers you trust and can compare against.
The Stress-Testing Loop
A stress test runs both solutions on many small random inputs and compares the results. If they ever disagree, you have found a bug, along with the exact input that triggers it. Use small inputs for three reasons:
- The brute force stays fast, so you can run thousands of trials in under a second.
- Small value ranges such as -5 to 5 produce duplicates, zeros, and negatives often. Those are the cases where bugs tend to hide.
- A failing input with five elements is easy to trace by hand.
A Complete Stress Test for Two-Sum
The script below contains both solutions and the test harness, so you can run it as shown.
import random
def two_sum_brute(nums, target):
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if nums[i] + nums[j] == target:
return (i, j)
return None
def two_sum_fast(nums, target):
seen = {}
for j, x in enumerate(nums):
if target - x in seen:
return (seen[target - x], j)
seen[x] = j
return None
def stress_test(trials=1000):
for _ in range(trials):
nums = [random.randint(-5, 5) for _ in range(random.randint(0, 8))]
target = random.randint(-10, 10)
a = two_sum_brute(nums, target)
b = two_sum_fast(nums, target)
assert (a is None) == (b is None), (nums, target, a, b)
if b is not None:
i, j = b
assert i != j and nums[i] + nums[j] == target, (nums, target, b)
print("all tests passed")
if __name__ == "__main__":
random.seed(0)
stress_test()Each assertion carries the failing input as its message. When a check fails, the traceback shows exactly which nums and target broke the code.
Compare Properties When Answers Can Differ
The test does not check a == b. Many inputs contain more than one valid pair. The brute force returns the pair with the smallest first index, and the fast version returns the pair whose second index comes earliest. On nums = [1, 4, 3, 2] with target = 5, brute force returns (0, 1). The fast version also returns (0, 1) here, but on [2, 4, 1, 3] with target = 5 the two differ: brute force gives (0, 3) and the fast version gives (1, 2). Both answers are correct.
So the test checks what must be true of any correct answer:
| Check | Why it matters |
|---|---|
| Both find a pair, or neither does | The oracle settles whether a solution exists |
| `i != j` | An element cannot be paired with itself |
| `nums[i] + nums[j] == target` | The returned pair actually works |
Common Mistakes
- Inputs that are too large. If the brute force takes seconds per trial, you run few trials and catch little.
- Value ranges that are too wide. With values from -1,000,000 to 1,000,000, duplicates almost never appear, so duplicate-handling bugs go unnoticed.
- Forgetting empty and one-element inputs. Let the generated length start at 0.
- Not seeding the generator. Call
random.seed(...)so you can reproduce a failure after you change the code. - Trusting a brute force you have not checked. The oracle is only as good as its own correctness, so test it on a few hand-worked cases first.
Exercise
Suppose twosumfast is changed so that seen[x] = j runs before the if target - x in seen check. What is the smallest kind of input on which the stress test fails, and which assertion catches it?
Show answer
A single element x where x + x == target, for example nums = [3] with target = 6. The buggy version stores 3 at index 0, then finds 6 - 3 in seen and returns (0, 0). Brute force returns None because there is no second index. The first assertion fails, since one result is None and the other is not. On inputs that do contain a valid pair, a self-pair like (0, 0) would instead be caught by the i != j check.
Exercise
Why does the generator draw values from -5 to 5 rather than from a wide range?
Show answer
A narrow range makes repeated values, zeros, and pairs that sum to the target common, so edge cases appear in many trials. With a wide range, most inputs have no valid pair and no duplicates, and those paths go almost untested.