Representing records, arrays and persistent text
By UK A Level Computer Science · independent study · myAudience
![Two-by-three readings matrix with rows [3,5,2] and [7,0,4], totals 10 and 11, and highlighted values[1][2]=4. Two text lines become signed-integer records.](/assets/lesson-computing-advanced-records-v1.webp)
Original textbook concept plate generated with OpenAI imagegen; labels and states checked against the lesson model. · Generated original teaching artwork; pending operator rights/provenance review before publication.
Representing records, arrays and persistent text
A record groups named fields describing one entity; an array groups indexed elements under a consistent representation. A two-dimensional rectangular array can model a matrix with row and column indices. Our original readings table uses rows for devices and columns for successive sampling times. Choosing these meanings is a modelling decision, so an answer such as “position [1][2]” needs both the indexing convention and the axis meanings. Python lists provide an array-like representation, but can change length and contain heterogeneous values; a fixed homogeneous array in another language has different guarantees.
For [[3,5,2],[7,0,4]], there are two rows and three columns. With zero-based indices, row 1 column 2 stores 4. The row totals are 10 and 11. Summing each row requires rc additions up to constant differences for r rows and c columns, giving Θ(rc) time and Θ(r) output storage. A ragged structure such as [[3,5],[7]] does not have one common column count. Rejecting it is meaningful when the application promises a rectangular matrix; treating it as a collection of independent lists would be a different contract.
Repeated references can corrupt a supposed grid. The expression [[0]*3]*2 creates one inner row and repeats its reference. Setting grid[0][1]=9 also changes the apparent second row. The expression [[0]*3 for _ in range(2)] constructs two independent rows. This extends the aliasing lesson from one-dimensional lists to multidimensional representations. The issue is identity, not simply whether brackets appear twice. A test must check that modifying one row leaves another unchanged when row independence is promised.
A file stores data beyond one execution. Text files encode characters into bytes using a chosen encoding; binary files store bytes whose interpretation depends on a format. Text is still physically binary on storage. A record layout must specify separators, field types, escaping and encoding, not only “save the list”. Our demonstration format has exactly two comma-separated fields per line, a device label and an integer reading. It deliberately does not support quoted commas within labels. Its limitations are stated rather than concealed by an apparently general filename.
parse_readings takes text rather than opening a file, which lets us test parsing independently of file permissions and storage failures. A boundary layer can open a fictional local file with an explicit UTF-8 encoding and pass the text to this pure parser. The parser reports the failing line if a field count or integer conversion is wrong. Missing files, malformed content and an empty valid file are different outcomes. Closing files through a context manager is good resource practice; it does not make an interrupted write transactional. This cohort teaches representation and parsing, with binary-file format construction left pending.
Reading the diagram: The matrix panel uses zero-based device/time indices: values[1][2] selects the highlighted 4, not the displayed row total. Totals 10 and 11 are derived outputs rather than a fourth input time column. The text panel represents two separate lines, north,10 and south,-2, converted to label/integer records. Labels in the conceptual record boxes are strings, not Python variable names. The negative measurement remains valid here because this parser does not use a sentinel contract.
Runnable original Python 3, independently executed on Python the related topic. Read the stated input contract before running. These examples use fictional data and are teaching models, not production services.
```python
def row_totals(rows):
"""Sum independent rectangular rows; reject ragged representations."""
if rows and any(len(row) != len(rows[0]) for row in rows):
raise ValueError('ragged matrix')
return [sum(row) for row in rows]
def parse_readings(text):
"""Parse original comma-separated integer records, preserving line errors."""
result = []
for number, line in enumerate(text.splitlines(), 1):
fields = line.split(',')
if len(fields) != 2:
raise ValueError(f'line {number}: two fields required')
try:
value = int(fields[1])
except ValueError as error:
raise ValueError(f'line {number}: integer required') from error
result.append((fields[0], value))
return result
```
Worked example: Parse the text "north,10
south,-2" and interpret a two-by-three readings matrix.
Split the fictional text into two lines, then split each line into exactly two fields.
Convert the second fields to integers, obtaining [("north",10),("south",−2)]. Negative readings are valid in this parser, unlike the sentinel model in lesson 3.
For [[3,5,2],[7,0,4]], sums are 3+5+2=10 and 7+0+4=11. The same data type can support different application contracts.
Answer: The parsed records preserve labels and signed integer values; the rectangular matrix has row totals [10,11].
Check your understanding: 1. Which cell stores 5 in the matrix? 2. Explain the failure for "north,ten". 3. A new label is "north,annex". Why does the existing format fail, and how should the interface change?
Answer: 1. [0][1] under zero-based indexing. 2. The second field cannot be converted to an integer, so a line-specific ValueError is raised. 3. That label would create three fields when combined with the reading. Adopt a documented escaping/quoting scheme and a compatible parser, or a structured format, and version the format. Do not discard extra fields or silently merge them without a rule.
Why: Text and binary describe interpretation and encoding, not whether storage uses bits. A negative measurement need not be a sentinel outside the sentinel contract. A format change is an interface change. Repeated rows can be aliases, so matching displayed values does not establish independent storage.