Skip to content

A simple version as referee

Read · 1 of 3

Slow and obviously right

Clever code is hard to check by reading. Simple code, like trying every pair, is easy to believe. So write the simple version too, run both on lots of small random inputs, and stop at the first input where they disagree.

That's called stress testing, and it's how competitive programmers and engineers find bugs no human would think of.

1import random
2
3for _ in range(1000):
4 nums = [random.randint(-5, 5) for _ in range(random.randint(1, 8))]
5 if fast(nums) != simple(nums):
6 print("Disagree on", nums)
7 break
Read this lesson as text

A slow but obviously correct version catches bugs in a clever one.

Slow and obviously right

Clever code is hard to check by reading. Simple code, like trying every pair, is easy to believe. So write the simple version too, run both on lots of small random inputs, and stop at the first input where they disagree.

That's called stress testing, and it's how competitive programmers and engineers find bugs no human would think of.

import random

for _ in range(1000):
    nums = [random.randint(-5, 5) for _ in range(random.randint(1, 8))]
    if fast(nums) != simple(nums):
        print("Disagree on", nums)
        break

Exercise: Write the referee

Read n and k, then n whole numbers. Print how many pairs of positions i < j have nums[i] + nums[j] == k.

Write the simple version: try every pair. It doesn't need to be fast.

They disagree

n, k = map(int, input().split())
nums = list(map(int, input().split()))
count = {}
for x in nums:
    count[x] = count.get(x, 0) + 1
pairs = 0
for x in nums:
    pairs += count.get(k - x, 0)
print(pairs // 2)

This fast version and your simple one disagree on k = 2, numbers 1 1 1. Which is wrong?

  • The fast one: when k - x == x, it pairs a number with itself
  • The simple one
  • Neither: that input isn't allowed
Show the answer

The fast one: when k - x == x, it pairs a number with itself. For each 1 it counts all three 1s, including itself, so it gets 9 // 2 = 4 instead of 3. The simple version is easy to trust, which is the whole point of a referee.