Pattern Recognition
intermediate25 minLearning objectives
- Recognise recurring patterns in computational problems
- Generalise solutions across similar problems
- Identify opportunities for code reuse
Learn
AQA 4.4.3 — Thinking procedurally: pattern recognition
Retrieval: the previous lesson broke problems into sub-problems. Pattern recognition looks across several decomposed sub-problems (possibly from entirely different projects) and asks: have I actually solved this exact shape of problem before?
Worked example — spotting the pattern
def validate_username(name):
if len(name) >= 3 and name.isalpha():
return True
return False
def validate_product_code(code):
if len(code) >= 3 and code.isalnum():
return True
return False
These look like two unrelated functions, but the pattern is identical: check a minimum length, then check the characters match a required type. Recognising that pattern lets you replace both with one general, reusable function:
def is_valid(value, kind):
if len(value) < 3:
return False
if kind == "username":
return value.isalpha()
elif kind == "code":
return value.isalnum()
return False
Common mistake
Generalising too early or too aggressively — trying to build one "does everything" function before you've actually seen the repeated pattern occur more than once. Pattern recognition works from real, observed repetition, not from guessing what might repeat in the future; over-generalised code is often harder to read and maintain than the duplication it was meant to remove.
Apply it — find the pattern yourself
Look back at the arithmetic operations, string manipulation and relational/Boolean operators lessons from Sequence 1. Identify one pattern that appears in more than one of those lessons' worked examples or challenges (for example: multiple examples validate user input against some rule before proceeding). State the pattern in general terms, and explain how a single reusable function could replace the repeated versions.
Challenge
Identify three separate examples of a repeated pattern from any lessons you've studied so far in this course (not just Sequence 1), state each pattern in one sentence, and for one of them, sketch (in words or code) what a single generalised, reusable version would look like.
Looking ahead: the next lesson (Algorithmic Thinking) uses exactly this kind of pattern-spotting as one of the tools for designing a brand new algorithm, rather than just tidying up existing code.