Edexcel International Advanced Level Computer Science, point 10.1.3
Pattern recognition means noticing similarities between problems, so that you can reuse a solution that already works. In Unit 2 you must be able to use the same or similar solution, algorithm or subprogram, or the same or similar data structure, in a different problem.
The idea
Many problems look different but have the same structure. If you recognise the pattern, you don't start from scratch.
| Different-looking problems | Same pattern |
|---|---|
| Find the highest mark, the tallest person, the most expensive item | Find the largest value in a list |
| Add up scores, prices, distances | Running total in a loop |
| Find a name in a class list, a word in a dictionary, a product code | Search |
| Undo in an editor, the back button, bracket checking | Stack |
| Print jobs, customers waiting, processes waiting for the CPU | Queue |
| Count vowels, count passes, count words | Counting items that meet a condition |
Reusing a solution, algorithm or subprogram
The same algorithm (here, find the largest) works for any list:
def find_largest(items):
largest = items[0]
for item in items[1:]:
if item > largest:
largest = item
return largest
print(find_largest([4, 9, 2])) # marks: 9
print(find_largest([1.5, 3.2, 2.8])) # prices: 3.2
print(find_largest(["cat", "zebra", "ant"])) # strings: zebra
The same counting pattern applied to different conditions:
def count_matches(items, condition):
count = 0
for item in items:
if condition(item):
count += 1
return count
marks = [45, 72, 38, 90, 55]
print(count_matches(marks, lambda m: m >= 50)) # 3 passes
words = ["apple", "kiwi", "banana"]
print(count_matches(words, lambda w: w.startswith("b"))) # 1
Here the pattern is "go through the items and count the ones that meet a test". Only the test changes.
Reusing a data structure
The same structure suits similar problems:
- A dictionary works for phone book, word counts, student marks by name, and a shop's prices: look up a value by a key.
def group_by_first_letter(words):
groups = {}
for word in words:
key = word[0].upper()
if key not in groups:
groups[key] = [] # a new list for a new letter
groups[key].append(word)
return groups
print(group_by_first_letter(["Amy", "Ben", "Ali"]))
# {'A': ['Amy', 'Ali'], 'B': ['Ben']}
print(group_by_first_letter(["pen", "paper", "ruler"]))
# {'P': ['pen', 'paper'], 'R': ['ruler']}
- A 2D list works for a noughts and crosses board, a seating plan, and a spreadsheet of marks.
- A stack works for undo, reversing a word, and checking brackets.
How to spot a pattern
- Ask: have I solved something like this before?
- Describe the problem in general terms (remove the specific details).
- Compare the inputs, outputs and steps with problems you know.
- Look for repeated structures in your own code (the same loop written twice).
- If you find repetition, turn it into a subprogram.
Benefits
- Saves time: reuse tested code.
- Fewer errors: proven solutions.
- Shorter, simpler code.
- Easier to maintain: fix a pattern in one place.
- Helps you solve new problems faster.
Worked example
Task: show how the same pattern solves (a) the total of a list of prices, and (b) the total length of a list of words.
Pattern: "combine every item into a running result."
def total_of(items, measure):
total = 0
for item in items:
total = total + measure(item)
return total
prices = [2.50, 4.00, 1.25]
print(total_of(prices, lambda p: p)) # (a) 7.75
words = ["data", "science", "is", "fun"]
print(total_of(words, len)) # (b) 4 + 7 + 2 + 3 = 16
Same algorithm and subprogram, with only the measure changing. A third problem (total of squares, lambda n: n * n) reuses it again.
Exam tip: when asked to show pattern recognition, name the common pattern (such as "find the largest", "running total", "search") and show the same subprogram or structure used in two different problems. Say what stays the same and what changes.
Check yourself
What is pattern recognition in programming?
Noticing that different problems share the same structure, so the same solution, algorithm, subprogram or data structure can be reused.
Name the common pattern in: highest mark, tallest person, dearest item
Finding the largest value in a list.
Give two benefits of reusing a known solution
Any two of: saves time; fewer errors because it is tested; shorter code; easier to maintain.
What should you do if you notice the same code written twice?
Turn it into a subprogram and call it from both places.