Edexcel International Advanced Level Computer Science, point 10.1.4
Generalisation means making a solution work for many similar problems, not just one. In Unit 2 you must be able to use a solution, algorithm or subprogram for similar problems by changing the input parameters.
The idea
A specific solution has values fixed in the code. A general one takes those values as parameters.
Specific (only works for one case):
def area_of_room_5_by_4():
return 5 * 4
General (works for any room):
def area_of_rectangle(width, height):
return width * height
print(area_of_rectangle(5, 4)) # 20
print(area_of_rectangle(2.5, 3)) # 7.5
print(area_of_rectangle(10, 10)) # 100
How to generalise
- Find the values that are fixed (numbers, strings, limits, file names).
- Replace each with a parameter.
- Give the parameters meaningful names.
- Check the code still works for the original case and for new ones.
- Add default values for the most common case if useful.
Examples
A general search
def search_list(items, target):
for i in range(len(items)):
if items[i] == target:
return i
return -1
print(search_list([4, 8, 15], 8)) # numbers: 1
print(search_list(["a", "b", "c"], "c")) # strings: 2
The same subprogram works for any list and any target.
A general validation routine
def get_choice(prompt, options):
while True:
reply = input(prompt).strip().lower()
if reply in options:
return reply
print("Please type one of:", ", ".join(options))
option = get_choice("Menu (1, 2 or 3): ", ["1", "2", "3"])
again = get_choice("Play again (y/n)? ", ["y", "n"])
One subprogram does the job of many, with different options passed in.
Default parameters
def discount(price, percent=10):
return price * (100 - percent) / 100
print(discount(80)) # uses the default 10% off: 72.0
print(discount(80, 25)) # 25% off: 60.0
A general data structure
A 2D list can hold any grid; a function can handle any size:
def make_grid(rows, cols, fill=0):
return [[fill] * cols for _ in range(rows)]
board = make_grid(3, 3, " ") # noughts and crosses
seats = make_grid(10, 20, "free") # a seating plan
Generalising a sort or a search
The bubble sort from 10.3.3 sorts any list of comparable items, in any order, if you pass in the list (and optionally a direction):
def bubble_sort(items, descending=False):
n = len(items)
for _ in range(n - 1):
for i in range(n - 1):
a, b = items[i], items[i + 1]
if (a < b) if descending else (a > b):
items[i], items[i + 1] = b, a
return items
print(bubble_sort([5, 2, 9, 1])) # [1, 2, 5, 9]
# ['pear', 'apple']
print(bubble_sort(["pear", "apple"], descending=True))
Generalisation and the other techniques
| Technique | Question it answers |
|---|---|
| Abstraction (10.1.1) | What can I hide? |
| Decomposition (10.1.2) | How can I split this up? |
| Pattern recognition (10.1.3) | Have I seen this before? |
| Generalisation | How can I make it work for similar cases? |
Benefits
- Reuse: one subprogram for many uses.
- Less code, so fewer places for errors.
- Easier to change: fix it once.
- More flexible: works for new data without rewriting.
Drawback
- Over-generalising makes code harder to understand and slower, with too many parameters. Generalise only as much as needed.
Worked example
Task: this code works out the cost of 3 adult tickets at £12.50. Generalise it.
total = 3 * 12.50
print("Total: £" + str(total))
Generalised:
def ticket_cost(quantity, price_each):
return quantity * price_each
print("Total: £" + format(ticket_cost(3, 12.50), ".2f")) # £37.50
# child tickets
print("Total: £" + format(ticket_cost(2, 8.00), ".2f"))
print("Total: £" + format(ticket_cost(5, 12.50), ".2f")) # a group
Changing the parameters (quantity, price_each) reuses the same subprogram for any number of tickets and any price.
Exam tip: generalising means replacing fixed values with parameters. Show the same subprogram called with different arguments. Pick meaningful parameter names, and check the original case still works.
Check yourself
What does generalisation mean?
Making a solution work for many similar problems, usually by replacing fixed values with parameters.
How can you generalise area_of_room_5_by_4()?
Make width and height parameters: area_of_rectangle(width, height).
What does a default parameter allow?
The subprogram can be called without that argument, using a sensible default value for the common case.
What is one risk of over-generalising?
The code becomes harder to understand and use, with too many parameters.