Strings, lists and records · GCSE · OCR J277 2.2.3, AQA 8525 3.2.6, Edexcel 1CP2 6.2.2 · about 15 min
Loops over items and indexes, totals, counts, min and max, and linear search.
[1 mark]What does this program print?
total = 0
for r in [4, 7, 9]:
total = total + r
print(total / 3)6.666666666666667
The running total is 20, and the average is 20 divided by 3.
[1 mark]What does this program print?
colours = ["red", "green", "blue"]
for i in range(len(colours)):
print(i, colours[i])0 red 1 green 2 blue
range(len(colours)) gives every valid index, 0 to 2.
[1 mark]What does this program print?
readings = [41, 35, 30, 25]
count = 0
for r in readings:
if r < 32:
count = count + 1
print(count)2
Only 30 and 25 are under 32.
[1 mark]A linear search finds its target at index 2. Why does it use break?
[1 mark]How does a linear search work?
[1 mark]What does this program print?
readings = [40, 36, 25]
for i in range(1, len(readings)):
print(readings[i - 1] - readings[i])4 11
Starting at index 1 means each item can be compared with the one before it.
Drive forward in five steps of 8 cm, recording distance() before each step in a list. Then print four lines: readings: <the list>, smallest: <cm>, largest: <cm> and average: <cm>. Work the average out with a loop or with sum and len, not by typing numbers.
# the two lines every program starts with: the commands, then the robot from bugbot import * connect() readings = []
The hint students can ask for: Take a reading, move a short way, and repeat, adding each reading to a list as you go. The smallest, largest and average all come from that list afterwards.
from bugbot import *
connect()
readings = []
for i in range(5):
readings.append(distance())
forward(50, distance=8)
print("readings:", readings)
print("smallest:", min(readings))
print("largest:", max(readings))
print("average:", sum(readings) / len(readings))
Any program that meets the task's checks is marked correct in the simulator; this is one way, not the only way.