Writing and Refining Algorithms
To refine an algorithm is to improve it: making it more efficient, or modifying or editing it to meet new requirements. A refined version must still solve the same problem, but with fewer unnecessary steps or with new rules built in.
If an algorithm contains several lines that do the same job and only a value changes, a loop does the job in one place. That makes the algorithm shorter and easier to update: the loop body is written once, so a change to it affects every repetition. The program below prints three warm-up steps from a list rather than using three separate print lines.
steps = ["jog", "stretch", "sprint"]
for step in steps:
print(step)Output:
jog
stretch
sprint
Separate if statements are each tested, even after one has already matched. Replace them with if, elif and else when only one branch should run. Once a condition matches, the later checks are skipped, which is more efficient and prevents two messages being output for the same input.
Validation rejects invalid input and asks for it again. Put the input inside a condition-controlled loop, and include the input line again inside the loop; otherwise the same invalid value is tested for ever. A constant stores a value that never changes while the program runs. Write its name in capital letters, such as MAX_HOURS, and set it once at the top. If the limit later changes, you edit one line rather than searching for every copy of the number.
The next program uses a constant for the maximum hire hours, rejects values outside 1 to 5, and then chooses one message with if, elif and else.
MAX_HOURS = 5
hours = int(input("Hours? "))
while hours < 1 or hours > MAX_HOURS:
print("Invalid")
hours = int(input("Hours? "))
if hours == 1:
print("Short hire")
elif hours <= 3:
print("Half day")
else:
print("Full day")Output when the user types 0, 3:
Hours? 0
Invalid
Hours? 3
Half day OCR GCSE Computer Science · Writing and Refining Algorithms