Editor

Update Marks in a Binary File

#614 · File handling · Advanced · 115 XP · about 20 min

A school saves each student as a list [roll, name, marks] in a binary file, one pickle.dump call per record. A teacher has a dictionary of corrections, mapping roll numbers to new marks.

Write update_marks(filename, changes) that applies the corrections to the file:

  • Every record whose roll number is a key of changes gets the new marks. If two records share a roll number, both are updated.
  • A new mark below 0 or above 100 is a typing mistake: leave that record as it is.
  • Roll numbers in changes that are not in the file are ignored.
  • Save all the records back into the same file, in their old order and still one pickle.dump per record.

Return a list of the roll numbers that were updated, from smallest to largest, each one once.

Example

If class.dat holds [1, 'Asha', 88], [2, 'Ben', 72] and [3, 'Cara', 65]:

update_marks('class.dat', {2: 80, 3: 120, 7: 50})  # returns [2]

The file now holds [1, 'Asha', 88], [2, 'Ben', 80] and [3, 'Cara', 65]: 120 is not a valid mark, and there is no student 7.

Constraints

  • The file holds at most 10,000 records.
  • A new mark equal to the old one still counts as an update.

Note

Opening a file with 'wb' empties it at once, so read every record first and close the file before you write.

Fastest solvers

Leaderboard

First solves only, ranked by stars and then time.