Strings, lists and records · GCSE · OCR J277 2.2.3, AQA 8525 3.2.6, Edexcel 1CP2 6.3.1 · about 15 min
Grouping related fields: a sensor reading as a record, and a list of records as a table.
[1 mark]What makes a record different from an array?
[1 mark]What does this program print?
reading = {"heading": 90, "distance": 51.0}
reading["heading"] = 180
print(reading["heading"], reading["distance"])180 51.0
A field is reached by its name, and can be changed like a variable.
[1 mark]What does this program print?
log = [{"h": 0, "d": 31}, {"h": 90, "d": 51}, {"h": 180, "d": 15}]
best = log[0]
for r in log:
if r["d"] > best["d"]:
best = r
print(best["h"])90
Keeping the whole record means the heading of the largest distance comes with it.
[1 mark]A robot log stores a time, a heading, a distance and a note for each reading. Which data types suit the fields?
Tick every answer that is true.
[1 mark]In a table of records, what is each row?
The robot is boxed in on three sides. Look in four directions, 90 degrees apart, storing each look as a record with the fields heading and distance in a list. Then print one line per record as heading 0: 31.0 cm, and finally print closest heading: <heading> for the record with the smallest distance.
# the two lines every program starts with: the commands, then the robot
from bugbot import *
connect()
log = []
for i in range(4):
turn_right(30, angle=90)The hint students can ask for: Store each reading as a record with the direction it was taken in, and add it to a list before turning. Afterwards, loop over the list to print, and keep the record with the smallest distance.
from bugbot import *
connect()
log = []
for i in range(4):
log.append({"heading": i * 90, "distance": distance()})
turn_right(30, angle=90)
for r in log:
print(f"heading {r['heading']}: {r['distance']} cm")
closest = log[0]
for r in log:
if r["distance"] < closest["distance"]:
closest = r
print("closest heading:", closest["heading"])
Any program that meets the task's checks is marked correct in the simulator; this is one way, not the only way.