SECTION 07 / 24

Collect everyone at the top three distinct mark levels

1 min read
Cutoffs are Maths 89, Physics 88 and Chemistry 92. They are the third distinct highest marks, not exactly three students.
Cutoffs are Maths 89, Physics 88 and Chemistry 92. They are the third distinct highest marks, not exactly three students.

The earlier TopThreeMarks procedure finds distinct score levels. Maths has levels 97, 93 and 89; Physics 92, 91 and 88; Chemistry 97, 93 and 92. Include every student whose mark is at least the third level. Ties mean a subject’s list can contain more than three people.

REAL COURSE DATA · BUILD AND UNPACK LISTS

Collect subject topper IDs

Follow one occurrence at a time. Choose another input to test empty lists, repeated IDs and different parameters.

Ready

CURRENT RECORD / VALUE

Ready to begin

No records have been processed. Start with Next step.

What we remember

Processed
0

Predict the next change, then step through the list. The original course records remain unchanged.

MathsIDs = []; PhysicsIDs = []; ChemistryIDs = []
foreach X in ScoreRecords:
    if X.Mathematics >= 89:
        MathsIDs = MathsIDs ++ [X.CardNo]
    if X.Physics >= 88:
        PhysicsIDs = PhysicsIDs ++ [X.CardNo]
    if X.Chemistry >= 92:
        ChemistryIDs = ChemistryIDs ++ [X.CardNo]
SubjectIDsNumber of students
Maths[11,14,20,23]4
Physics[5,7,9,11,18,23]6
Chemistry[11,14,18,25]4

Learn the cutoffs first, then construct membership lists with fixed cutoffs. Three independent IF statements let Rahul enter all three lists. Using strict > would wrongly discard students exactly at the boundary. Computing the cutoffs by separate consuming table scans also requires restoring the table between calls.

The lecture’s zero-initialized top-three procedure relies on non-negative marks and this dataset having enough positive distinct scores. A general implementation should use empty slots or an explicit unavailable result when fewer than three distinct values exist. Equality must not shift a repeated top mark into a new distinct level.

Try it yourself

Why are there four Maths IDs rather than three?

Show explained answer

97 is shared by Rahul and Deepika. The top three distinct levels include everyone scoring 97, 93 or 89.

Try it yourself

Does Chemistry 92 qualify when the cutoff is 92?

Show explained answer

Yes. Use ≥, including the boundary.

Try it yourself

What must happen before reusing a consuming TopThreeMarks table procedure?

Show explained answer

Restore the input records according to its contract so every subject call sees the full dataset.

YOUR STUDY PROGRESS

Finished this section? Save your progress.

Back to top ↑