Generate candidate solutions, test them against explicit constraints, and stop when a valid solution is found or the candidate space is exhausted.
01
Learning objectives
Explain the Generate-and-Test strategy and its two main operations.
Describe when exhaustive candidate generation is practical.
Use constraints or heuristics to reduce unnecessary tests.
Recognise why this method may become expensive as the search space grows.
02
Lesson notes
Generate-and-Test is a problem-solving method that repeatedly creates a candidate solution and checks whether it satisfies the required conditions. A generator produces a possible answer; a tester evaluates it. If the candidate is incorrect, the method generates another. It stops when a satisfactory candidate is found or when all available candidates have been considered.
The approach is useful when the candidate space is small enough to explore, when no direct solution strategy is apparent, or when constraints can reduce the number of candidates. For example, a simple puzzle can be solved by generating possible combinations and checking each against the rules.
The method is easy to understand but may require many attempts. If there are k independent positions with n choices each, the number of possible candidates can grow as n to the power k. A heuristic can prioritise promising candidates or prune options that violate a known constraint before completing the entire candidate.
A candidate generator should define the search space and avoid missing valid possibilities. A tester should implement the actual problem conditions. If either component is incomplete, the method may falsely reject a valid solution or accept an invalid one.
03
Worked code examples
Worked example
The generator enumerates pairs in a defined search space. The tester applies both the sum constraint and an ordering rule, and the loop stops at the first accepted candidate.
from itertools import product
digits = range(10)
target = 12
for a, b in product(digits, repeat=2):
candidate = (a, b)
if a + b == target and a <= b:
print("Candidate accepted:", candidate)
break
Output
Candidate accepted: (3, 9)
04
Key terminology
Candidate
A possible solution generated for testing.
Generator
The part of the method that creates possible solutions.
Tester
The part that checks a candidate against the problem constraints.
Pruning
Rejecting a partial candidate early when it cannot lead to a valid solution.
05
Common misconceptions
Common mistake
Generate-and-Test always finds an answer quickly.
Correct understanding
Its cost depends on the size and structure of the search space; some spaces are too large to enumerate efficiently.
Common mistake
A candidate is correct because it was generated.
Correct understanding
Every candidate must be checked against all required conditions.
06
Check your understanding
1. What are the two core steps of Generate-and-Test?
2. When is exhaustive Generate-and-Test most practical?