Computational
Thinking 3
Tables for data, procedures and parameters, the three prizes problem, and side effects. Lectures 3.1 to 3.9.
Chapters
Presentation of Datasets as Tables
Cards as rows of a table, and why a bill with a variable number of items must be split into linked tables.
Data usually arrives on cards: a grade card, a card for a word, a shopping bill. This lecture shows how to lay such data out as a table, and what goes wrong when a card has a variable amount of information, like a bill with any number of items.
1.1Extracting data from cards
- Each card is a unit of information.
- A card has different attributes (also called fields): Card ID, Name, Gender, ..., Total.
- Organise the cards as a table: each attribute is a column and each card is a row.
- All the grade cards go together in a single table.
| Id | Name | Gen | DoB | City | Math | Phys | Chem | Total |
|---|---|---|---|---|---|---|---|---|
| 10 | Kavya | F | 12 Jan | Chennai | 64 | 72 | 68 | 204 |
| 24 | Siddharth | M | 26 Dec | Madurai | 44 | 72 | 58 | 174 |
| 17 | Arshad | M | 14 Dec | Chennai | 62 | 81 | 67 | 210 |
The column headings are the attribute names. A card never has a "missing column": every card in the table has a value for every attribute, so the table stays neat.
1.2The same idea for words
Cards can hold anything that has attributes. For the words in a paragraph, each word is a card with an Id, the Word itself, its Type (noun, verb, ...) and its Length.
| Id | Word | Type | Length |
|---|---|---|---|
| 24 | Saturday | Noun | 8 |
| 12 | considered | Verb | 10 |
1.3Shopping bills: a table that is no longer neat
- Variable number of columns? A card cannot have a different number of columns. The table is no longer neat.
- Variable number of rows per card? Give a row to each item and tag the rows with the card (bill) Id.
Doing that gives one big table for the bill:
| Id | Shop | Customer | Item | Category | Qty | Price | Cost | Total |
|---|---|---|---|---|---|---|---|---|
| 5 | Big Bazaar | Akshaya | Trousers | Women/Apparel | 2 | 870 | 1740 | 4174 |
| 5 | Big Bazaar | Akshaya | Shirts | Women/Apparel | 1 | 1350 | 1350 | 4174 |
| 5 | Big Bazaar | Akshaya | Detergent | Household | 0.5 | 270 | 135 | 4174 |
| 5 | Big Bazaar | Akshaya | Tee Shirts | Women/Apparel | 4 | 220 | 880 | 4174 |
| 5 | Big Bazaar | Akshaya | Instant Noodles | Canned/Food | 3 | 23 | 69 | 4174 |
Id, Shop, Customer and Total are duplicated in each row of the table. The problem gets worse as the number of entries in the bill increases.1.4The fix: multiple tables
Split the bill into two tables. The first holds the columns that are fixed for the bill. The second holds the variable entries as multiple rows. The Bill ID links the two tables.
Cards with a fixed set of attributes fit one table. Cards with a variable number of entries are split into separate tables, linked by a unique attribute such as the Bill ID. The linking attribute must be unique for each bill, otherwise rows of two bills could be mixed up.
The same split works for any bill. Bill 1 from SV Stores (customer Srivatsan, total 567) has one row in the first table and many in the second: Carrots, Soap, Tomatoes, ..., Milk.
1.5Going deeper
- Why the link must be unique (extra). If two bills shared Id 5, a lookup of "Id = 5" in the items table would return rows from both, and totals would be wrong.
- Consistency checks. The bill-level
Totalmust equal the sum of the itemCosts, and eachCostmust equalQty × Price. A table lets you check both. - One-to-many. One row in table 1 matches many rows in table 2: that is the shape of every "variable number of entries" problem (extra).
1.6Exam tips and common mistakes
- Name the columns first, then fill one row per card.
- For a bill, ask "which facts are once per bill and which are once per item?" before drawing any table.
- One big table for a bill (Id, Shop, Customer, Total get copied into every row).
- Linking tables with an attribute that is not unique.
- Forgetting that every card has a value for every column.
Practice questions (graded-assignment style)
Numerical Answer Type (NAT).
In the grade-card table, what is the highest Total?
Compare 204, 174, 210.
- The largest total is 210, on Arshad's card (Id 17).
- Answer: 210
Numerical Answer Type (NAT).
What is the sum of the Maths marks of the three grade cards?
Add 64, 44, 62.
64 + 44 + 62 = 170.- Answer: 170
Numerical Answer Type (NAT).
A bill has 20 items. How many cells do the two linked tables use for the 4 bill-level facts plus the linking Id in each item row?
4 facts once, plus the Id in each of the 20 rows.
4 + 20 = 24(the single table would use4 × 20 = 80).- Answer: 24
Multiple Choice Question (MCQ): choose the one correct option.
Why is a bill split into two tables?
Which values repeat in the single table?
- Id, Shop, Customer and Total repeat in every row, and the repetition grows with the number of items. Two linked tables avoid it.
- Answer: option 2.
Numerical Answer Type (NAT).
How much did Akshaya spend on Women/Apparel items?
Find the rows with Id 5 and that category.
- Trousers 1740 + Shirts 1350 + Tee Shirts 880 = 3970.
- Answer: 3970
Multiple Select Question (MSQ): select all that apply.
Choose the correct statements.
Recall the two-table figure.
- Statements 1, 2 and 4 are true. The Total belongs to the fixed table (table 1), not the item rows.
- Answer: options 1, 2 and 4.
Attribute = column
Card = row
Item-level: Item, Qty, Price, Cost
Worse with more items
Item rows in another
Pseudocode for Procedures and Parameters, Part 1
Writing a loop once as a procedure, and filling in its blanks with parameters.
Last week the same loop was written again and again with small changes. A procedure is pseudocode written once as a template that works in different situations, with parameters to say which situation we mean.
2.1Why we need procedures
The sum of the boys' Maths marks uses X.Gender == M. What if we want the girls' Maths marks? Only the value checked against X.Gender changes; the remaining pseudocode is identical.
Sum = 0
while (Pile 1 has more cards) {
Pick a card X from Pile 1
Move X to Pile 2
if (X.Gender == M) {
Sum = Sum + X.Maths
}
}Sum = 0
while (Pile 1 has more cards) {
Pick a card X from Pile 1
Move X to Pile 2
if (X.Gender == F) {
Sum = Sum + X.Maths
}
}The flowchart changes in just one box too: the decision becomes X.Gender == F instead of X.Gender == M. Copying the whole loop for every small change is wasteful. A procedure lets us write it once.
2.2A procedure to sum Maths marks
Procedure SumMaths(gen)
Sum = 0
while (Pile 1 has more cards) {
Pick a card X from Pile 1
Move X to Pile 2
if (X.Gender == gen) {
Sum = Sum + X.Maths
}
}
return(Sum)
end SumMaths| Part | In SumMaths | Meaning |
|---|---|---|
| Name | Procedure SumMaths | the name used to call it |
| Argument | gen | receives a value on each call |
| Argument is used | X.Gender == gen | gen is compared with X.Gender |
return | return(Sum) | hands the value of Sum back |
end | end SumMaths | closes the procedure |
Calling the procedure with a parameter: SumMaths(F). The argument variable is assigned the parameter value: the call implicitly starts with gen = F. The procedure returns the value stored in Sum.
The name in the procedure heading (gen) is the argument. The value given in the call (F) is the parameter. The call copies the parameter into the argument.
2.3Changing the field: SumMarks(gen, fld)
For the Physics marks the only change is the field examined on the card: X.Physics instead of X.Maths. For Chemistry add up X.Chemistry, for the total X.Total. Writing a new procedure for each field is the same problem again, so pass the field name as a parameter too.
Procedure SumMarks(gen,fld)
Sum = 0
while (Pile 1 has more cards) {
Pick a card X from Pile 1
Move X to Pile 2
if (X.Gender == gen) {
Sum = Sum + X.fld
}
}
return(Sum)
end SumMarks| Call | gen | fld | What is added up |
|---|---|---|---|
SumMarks(F,Chemistry) | F | Chemistry | Girls' Chemistry marks |
SumMarks(M,Physics) | M | Physics | Boys' Physics marks |
SumMarks(M,Total) | M | Total | Boys' Total marks |
SumMarks(F,Maths) | F | Maths | Girls' Maths marks |
F) or a field name (Chemistry). Both are just assigned to the argument variables when the call starts. X.fld picks that entry on the card.2.4Calling a procedure
Use the procedure name like a maths function, as part of an expression, and assign the return value to a variable.
GirlChemSum = SumMarks(F,Chemistry)
BoyChemSum = SumMarks(M,Chemistry)
if (GirlChemSum ≥ BoyChemSum) {
"Congratulate the girls"
}
else {
"Congratulate the boys"
}A procedure may not return a value. For example, a procedure to correct the marks for one subject on a card, Procedure UpdateMarks(CardId, Subject, Marks) ... end UpdateMarks. Its call is a separate statement, not part of an expression: UpdateMarks(17,Physics,88).
Procedures modularize pseudocode: the same process is not described again and again. If we improve the code in a procedure, the benefit applies automatically to every call.
2.5Worked examples on eight cards
These eight cards are used in all the examples this week (example data, not from the lecture):
| ID | GENDER | MATHS | PHYSICS | CHEMISTRY |
|---|---|---|---|---|
| 1 | M | 95 | 93 | 40 |
| 2 | F | 94 | 40 | 95 |
| 3 | M | 96 | 94 | 41 |
| 4 | F | 40 | 96 | 94 |
| 5 | M | 42 | 95 | 96 |
| 6 | F | 80 | 82 | 81 |
| 7 | F | 60 | 60 | 60 |
| 8 | M | 70 | 70 | 70 |
2.6Going deeper
- Call by copying (extra). The parameter is copied into the argument, so changing
geninside the procedure does not change the caller's value. - Ignoring the result is a bug. A call like
SumMarks(F,Total)on its own line throws the answer away. Assign it. - Generalising. SumMaths → SumMarks is the pattern: find what changes between copies and turn each change into a parameter.
2.7Local and global variables: what a procedure can see and keep
A procedure uses variables of its own, such as Sum in SumMarks, and it can also see data that belongs to the program that calls it, such as the deck of cards. Knowing which is which explains why a procedure can be called again and again with different arguments and still give a correct answer.
A. Local variables start fresh on every call
The parameters (gen, fld) and every variable that the procedure sets up inside itself (Sum) are local: they exist only while that call is running. Each new call starts with a new Sum = 0. That is why the following two calls are independent:
Procedure SumMarks(gen, fld)
Sum = 0
while (Pile 1 has more cards) {
Pick a card X from Pile 1
Move X to Pile 2
if (X.Gender == gen) {
Sum = Sum + X.fld
}
}
return(Sum)
end SumMarks- On the eight cards (with the deck restored between the calls),
SumMarks(F,Physics)returns , andSumMarks(M,Physics)returns . The second answer does not include the first. - Two different procedures may use the same local name (
SuminSumMarks,Sumin some other procedure) without interfering. - Changing a parameter inside the procedure (
gen = M) changes only the local copy; the caller's value stays as it was.
B. What goes wrong when the total is kept outside
Suppose Sum = 0 is written once, outside the procedure, so Sum is a shared (global) variable that every call updates:
Sum = 0
Procedure SumMarks(gen, fld)
while (Pile 1 has more cards) {
Pick a card X from Pile 1
Move X to Pile 2
if (X.Gender == gen) {
Sum = Sum + X.fld
}
}
return(Sum)
end SumMarksNow the first call SumMarks(F,Physics) returns and leaves Sum = 278. The second call SumMarks(M,Physics) starts from that leftover: it returns , which is wrong. The call that is made first gets the right answer; every later call is contaminated by the earlier ones.
GirlPhy = SumMarks(F,Physics), BoyPhy = SumMarks(M,Physics)).C. Local values versus shared data
| Local (parameter or variable set up inside) | Shared (the deck of cards, a global variable) | |
|---|---|---|
| Exists | only during one call | before and after the call |
| A change inside the procedure | disappears when the call ends (it cannot change the caller's variable) | stays after the call: this is a side effect (see "Side Effects of Procedures") |
| Example | gen, fld, Sum | Pile 1 and Pile 2: moving cards from Pile 1 to Pile 2 changes the deck for whoever calls next |
This is the same distinction as in "Side Effects of Procedures": a procedure that moves the cards from Pile 1 to Pile 2 leaves Pile 1 empty, so a second call finds no cards unless the caller (or the procedure itself) puts them back.
2.8Exam tips and common mistakes
- To trace a call, first write down the implicit assignments (
gen = F,fld = Chemistry), then run the body. - To choose a call, name what changes (gender, field) and read the parameters in the heading order.
- Mixing up argument (in the heading) and parameter (in the call).
- Passing the parameters in the wrong order, e.g.
SumMarks(Chemistry,F). - Using a call without storing or using its return value.
Practice questions (graded-assignment style)
Numerical Answer Type (NAT).
What does SumMarks(F,Chemistry) return on the eight cards?
Add the Chemistry marks of the girls (cards 2, 4, 6, 7).
95 + 94 + 81 + 60 = 330.- Answer: 330
Numerical Answer Type (NAT).
What does SumMarks(M,Maths) return on the eight cards?
Boys are cards 1, 3, 5, 8.
95 + 96 + 42 + 70 = 303.- Answer: 303
Multiple Choice Question (MCQ): choose the one correct option.
Which call gives the sum of the girls' Physics marks?
SumMarks(M,Physics)SumMarks(Physics,F)SumMarks(F,Physics)SumMaths(F)The order is (gender, field).
- The heading is
SumMarks(gen,fld), so the girls' Physics marks areSumMarks(F,Physics)(278 on the eight cards). - Answer: option 3.
Multiple Choice Question (MCQ): choose the one correct option.
UpdateMarks(17,Physics,88) is used as:
Does it return a useful value?
- It returns nothing useful, so the call stands alone as a statement.
- Answer: option 2.
Multiple Select Question (MSQ): select all that apply.
In Procedure SumMarks(gen,fld) called as SumMarks(M,Total), choose the correct statements.
gen and fld are the argumentsM and Total are the parametersgen = M and fld = TotalTotal is the argumentArgument = name in the heading; parameter = value in the call.
- Statements 1, 2, 3 are true.
Totalis a parameter, not an argument. - Answer: options 1, 2 and 3.
Multiple Choice Question (MCQ): choose the one correct option.
What is the main benefit of using one procedure for the boys' and girls' sums?
Think of modularising.
- Procedures modularize pseudocode: write once, call often; an improvement applies to every call.
- Answer: option 2.
Numerical Answer Type (NAT).
On the eight cards of this week, Sum = 0 is written once outside SumMarks(gen, fld), and the procedure never resets it. The deck is restored between calls. The program calls SumMarks(F,Physics) and then SumMarks(M,Physics). What does the second call return?
Sum is shared, so the second call starts from the value the first call left behind.
- Girls' Physics: . After the first call,
Sum = 278. - Boys' Physics: . The second call keeps adding to 278: .
- With
Sum = 0inside the procedure, the second call would return . - Answer: 630
Multiple Select Question (MSQ): select all that apply.
Choose the correct statements.
Sum without interfering.Local data is created and discarded with each call; shared data (the deck) outlives the call.
- 1 ✗ Local variables start afresh on every call. 2 ✓ The parameter is a local copy. 3 ✓ The deck is shared, so this is a side effect. 4 ✓ Local names are private to their procedure.
- Answer: options 2, 3 and 4.
Multiple Choice Question (MCQ): choose the one correct option.
A student writes GirlChem = SumMarks(F,Chemistry) and then BoyChem = SumMarks(M,Chemistry). The first call gives 330, but BoyChem comes out as 577 instead of 247. What is the most likely cause?
gen was not copied.Sum = 0 is outside the procedure, so the second call continued from 330.return.Chemistry was misspelled.: the second answer contains the first.
- The boys' Chemistry sum is , and . An answer that equals the old total plus the new one points to an accumulator that was never reset.
- Options 3 and 4 would give an error or a wrong first answer, not a first answer that is right.
- Answer: option 2.
Template for many cases
Write once, call often
Arguments (gen, fld)
return(Sum), end name
Implicitly gen = F
A value or a field name
Statement: UpdateMarks(...)
Improve once, all calls gain
Boys Chemistry 247
Pseudocode for Procedures and Parameters, Part 2
One Maxmarks procedure for any field, and the analysis of top students built on it.
This lecture uses a procedure to answer questions about the top students. The idea: when the same computation is needed for different fields (Maths, Physics, Chemistry, Total), write it once as a procedure and let a parameter name the field.
3.1Analysis of top students
- Is there a single student who is the best performer across subjects?
- Is the highest overall total the same as the sum of the highest marks in each subject?
Both questions need the maximum for different fields: Maths, Physics, Chemistry and Total. So one procedure Maxmarks(fld), with the field as a parameter, fits.
3.2Finding the maximum in a given field
As usual keep track of the maximum with a variable: initialise it to 0 and update it whenever you see a bigger value. What is new is that the value being compared is not fixed: the parameter fld decides the field of interest.
Procedure Maxmarks(fld)
Maxval = 0
while (Pile 1 has more cards) {
Pick a card X from Pile 1
Move X to Pile 2
if (X.fld > Maxval) {
Maxval = X.fld
}
}
return(Maxval)
end MaxmarksMaxmarks(Maths) sets fld = Maths, so the test reads X.Maths > Maxval. Calling Maxmarks(Total) makes it X.Total > Maxval. The procedure itself never changes.3.3Using Maxmarks to compare the totals
Call Maxmarks four times, once for each category, with fld set appropriately. Save each return value in its own variable. Then use the saved values to compare the maximum overall total with the sum of the maximum subject marks.
MaxMaths = Maxmarks(Maths)
MaxPhysics = Maxmarks(Physics)
MaxChemistry = Maxmarks(Chemistry)
MaxTotal = Maxmarks(Total)
SubjTotal = MaxMaths + MaxPhysics + MaxChemistry
if (MaxTotal == SubjTotal) {
SingleTopper = True
}
else {
SingleTopper = False
}| Procedure call | Value on the 8 cards |
|---|---|
MaxMaths = Maxmarks(Maths) | 96 |
MaxPhysics = Maxmarks(Physics) | 96 |
MaxChemistry = Maxmarks(Chemistry) | 96 |
MaxTotal = Maxmarks(Total) | 243 |
SubjTotal = 96 + 96 + 96 | 288 |
MaxTotal == SubjTotal | 243 == 288 is False, so SingleTopper = False |
Each call produces a number that is needed later. Putting every return value into its own variable keeps track of the outcomes of the multiple procedure calls, so they can be added and compared.
MaxTotal == SubjTotal can only happen when one card holds the highest mark in all three subjects, which means there is a single top student. (This reading is worked out from the pseudocode; the slide only states the question and the code.)3.4Going deeper
- Same procedure, four jobs. Using one procedure for four fields avoids describing the same process repeatedly. If we improve the code in the procedure, every call gets the benefit.
- Parameters fix the context, variables keep the outcomes. The parameter says which field; the saved variables hold what came back.
- Ties for the top (extra).
MaxTotal == SubjTotalsays there is a single top student only in the sense "one card holds all three maxima"; it does not say which card. Use the card-id version of Week 2 for that.
3.5Exam tips and common mistakes
- Make a table of the four calls and their values first; the comparison is then one line.
- Remember the inequality: a total can never exceed the sum of the subject maxima.
- Calling
Maxmarkswithout saving the return value. - Starting
Maxvalat something other than a value below every mark. - Reading
X.fldas a field literally named "fld".
Practice questions (graded-assignment style)
Numerical Answer Type (NAT).
What does Maxmarks(Chemistry) return on the eight cards?
Look for the largest Chemistry mark.
- The largest Chemistry mark is 96, on card 5.
- Answer: 96
Numerical Answer Type (NAT).
What does Maxmarks(Total) return on the eight cards?
Compute each card's total first.
- The totals are 228, 229, 231, 230, 233, 243, 180, 210. The maximum is 243 (card 6).
- Answer: 243
Numerical Answer Type (NAT).
For the eight cards, what is SubjTotal - MaxTotal?
Use 288 and 243.
288 - 243 = 45: no card holds all three maxima.- Answer: 45
Multiple Choice Question (MCQ): choose the one correct option.
For the eight cards, SingleTopper is:
TrueFalse243Compare MaxTotal with SubjTotal.
243 == 288is False.- Answer: option 2.
Multiple Choice Question (MCQ): choose the one correct option.
MaxTotal == SubjTotal can be True only when:
No total can exceed the sum of the maxima.
- A total equals the sum of the three maxima only if that card has the maximum in each subject.
- Answer: option 2.
Numerical Answer Type (NAT).
Pile 1 has cards (90, 85, 80) and (70, 60, 75). What is MaxTotal?
Totals are 255 and 205.
- The larger total is 255 (card 1), equal to
SubjTotal = 90 + 85 + 80. - Answer: 255
Top total = sum of tops?
if X.fld > Maxval: update
return(Maxval)
Save each return value
MaxTotal == SubjTotal ?
288 vs 243: False
Variables keep the outcomes
Pseudocode for the Three Prizes Problem
A complex problem broken into procedures: top three marks, subject toppers and the three winners.
This lecture works out a complex problem in full detail: awarding three prizes. The trick is to break it into steps, turn the natural units into procedures, and then plug them together.
4.1The three conditions
- Basic criterion: total marks. Award prizes to the top 3 students.
- Must also be in the top three in at least one subject.
- Must select at least one boy and one girl among the three.
Everything starts from the basic pattern: find the top three marks in a category.
4.2Finding the top three marks, step by step
- The maximum: initialise
maxto 0, scan the cards, update each time you see a bigger value. - The top two: maintain
maxandsecondmax. If the current value is bigger thanmax, copymaxtosecondmaxand updatemax. If it is betweenmaxandsecondmax, leavemaxalone and updatesecondmax. - The top three: the same idea with one more slot,
thirdmax.
A new maximum pushes the old max into second place and the old second into third place. The old third falls out. Update the lowest slot first: third takes second, then second takes max, then max takes the new value. Doing it in the other order would overwrite values before they are copied.
4.3A procedure: top three marks in a subject
Procedure TopThreeMarks(Subj)
max = 0
secondmax = 0
thirdmax = 0
while (Pile 1 has more cards) {
Pick a card X from Pile 1
if (X.Subj > max) {
thirdmax = secondmax
secondmax = max
max = X.Subj
}
if (max > X.Subj > secondmax) {
thirdmax = secondmax
secondmax = X.Subj
}
if (secondmax > X.Subj > thirdmax) {
thirdmax = X.Subj
}
}
return(thirdmax)
end TopThreeMarksIn the pseudocode these are three separate if statements. Once one has updated the slots, X.Subj equals that slot, so the later tests are False. It is sufficient to return thirdmax, the third highest mark in the subject. (The procedure ought to return all three values as a list; lists come later in the course.)
TopThreeMarks (and of the main loop in 4.4) shows Pick a card X from Pile 1 but not Move X to Pile 2. Every earlier loop includes the move, which is what makes the loop end, so these notes keep the code exactly as on the slide and treat the move as understood.4.4The three prizes algorithm
The prize winners are the top three totals, but only among students who are in the top three in at least one subject. (The boy and girl requirement is dealt with later.) Again we maintain max, secondmax, thirdmax, now together with the card ids maxid, secondmaxid, thirdmaxid, because at the end we need to know who the winners are.
A card is in the top three of a subject exactly when its mark is at least the third highest mark of that subject. That is why we record maths3, phys3 and chem3 first and compare each card with them before updating max, secondmax, thirdmax.
max = 0
secondmax = 0
thirdmax = 0
maxid = -1
secondmaxid = -1
thirdmaxid = -1
maths3 = TopThreeMarks(Maths)
phys3 = TopThreeMarks(Physics)
chem3 = TopThreeMarks(Chemistry)
while (Pile 1 has more cards) {
Pick a card X from Pile 1
if (SubjectTopper(X,maths3,phys3,chem3)) {
if (X.Total > max) {
thirdmax = secondmax
thirdmaxid = secondmaxid
secondmax = max
secondmaxid = maxid
max = X.Total
maxid = X.Id
}
if (max > X.Total > secondmax) {
thirdmax = secondmax
thirdmaxid = secondmaxid
secondmax = X.Total
secondmaxid = X.Id
}
if (secondmax > X.Total > thirdmax) {
thirdmax = X.Total
thirdmaxid = X.Id
}
}
}maths3 in one place and math3 in another, and call the procedure as SubjectTopper(X,M,C,P) although its heading is (Card,MMark,PMark,CMark). These notes use maths3, phys3, chem3 consistently and pass the three third-highest marks in the order of the heading.4.5The procedure SubjectTopper
Compare each subject's marks on the card with the third highest mark. The marks are passed explicitly as parameters. One or more comparisons should succeed, which is what the or operator means.
Procedure SubjectTopper(Card,MMark,PMark,CMark)
if (Card.Maths ≥ MMark or
Card.Physics ≥ PMark or
Card.Chemistry ≥ CMark) {
return(True)
}
else {
return(False)
}
end SubjectTopperif (SubjectTopper(X,M,C,P) == True). Since the return value is already Boolean, we can simply write if (SubjectTopper(X,M,C,P)).4.6Boundary conditions
A good solution has to anticipate unexpected situations in the data. The lecture raises two.
>). So a later card whose total equals max, secondmax or thirdmax does not take that slot: the card that arrived first stays. This follows from the code as written; the slide only poses the questions.4.7When the code gives a wrong answer: ties (extra)
Because every comparison is strict, TopThreeMarks effectively finds the third highest distinct mark. That is fine when marks are all different, but ties can break the idea:
| Marks in the subject | TopThreeMarks returns | Why it matters |
|---|---|---|
96, 95, 94 | 94 | correct: the third highest mark |
96, 96, 95, 94 | 94 | the repeated 96 is ignored, so 94 is returned although only two cards are above it |
90, 90, 90 | 0 | thirdmax stays 0, so every card passes SubjectTopper |
So ties need a deliberate choice of rule (the lecture leaves this open): for example, decide whether equal marks share a place, and change the comparisons (> versus ≥) to match.
4.8Going deeper
- Break big problems into procedures. The prize problem is one loop plus two procedures (
TopThreeMarks,SubjectTopper); each is small enough to check on its own. - Will the exclusion always work? (extra) No: if fewer than three eligible cards remain, or all eligible cards have the same gender, repeating cannot produce a boy and a girl. A real solution must say what to do then.
- Total before subject. Card 6 has the best total but is not eligible: the subject condition filters first, then the total ranks.
4.9Exam tips and common mistakes
- Compute the three subject thresholds (
maths3,phys3,chem3) first, then mark each card Topper or not, then rank only the toppers. - Keep each slot as (total, id) pairs so the winners can be read off.
- Updating the slots in the wrong order and overwriting values before copying them.
- Forgetting to initialise the ids to -1.
- Awarding a prize to a card with the best total that is not a subject topper.
- Ignoring that all three winners can be of one gender.
Practice questions (graded-assignment style)
Numerical Answer Type (NAT).
What does TopThreeMarks(Maths) return on the eight cards?
The three highest Maths marks are 96, 95, 94.
- The third highest Maths mark is 94 (card 2).
- Answer: 94
Multiple Select Question (MSQ): select all that apply.
With maths3 = phys3 = chem3 = 94, which cards are subject toppers?
A card passes if any one mark is at least 94.
- Card 1 has Maths 95; card 4 has Physics 96 and Chemistry 94.
- Cards 6 (80, 82, 81) and 8 (70, 70, 70) have no mark of 94 or more.
- Answer: options 1 and 2.
Multiple Choice Question (MCQ): choose the one correct option.
Who wins the first prize in the eight-card run?
Card 6 has the best total but is not eligible.
- Among the eligible cards the highest total is 233, on card 5.
- Answer: option 2.
Numerical Answer Type (NAT).
In the same run, which card id gets the third prize?
The third-highest eligible total is 230.
- The winners are 5 (233), 3 (231), 4 (230): the third prize goes to card 4.
- Answer: 4
Multiple Choice Question (MCQ): choose the one correct option.
If card 4 were a boy, after excluding card 4 the third prize winner becomes:
Eligible cards are 1, 2, 3, 5; take the top three totals.
- The top three totals are card 5 (233), card 3 (231) and card 2 (229, a girl), so the condition now holds.
- Answer: option 2.
Multiple Select Question (MSQ): select all that apply.
Choose the correct statements about the code as written.
Strict comparisons never replace an equal value.
- Statements 1, 2 and 4 follow from the strict comparisons.
- Statement 3 is false: for 90, 90, 90 the procedure returns 0 (extra).
- Answer: options 1, 2 and 4.
Top three in some subject
At least one boy and one girl
A new value shifts the slots
TopThreeMarks returns thirdmax
Card.Maths ≥ MMark or ...
Returns True or False
maths3, phys3, chem3
Update totals and ids
Card 6 not eligible
Ties: how many tolerated?
Side Effects of Procedures
What a procedure changes besides its return value, and the contract that says what it promises.
A procedure can do more than return a value: it can change data while it runs. This lecture is about noticing those changes, called side effects, and about writing down what a procedure promises.
5.1Passing the deck of cards
The procedure SumMarks(gen,fld) works for one fixed set of cards, the cards in Pile 1. What about any set of cards? Pass the deck through a third parameter.
Procedure SumMarks(gen,fld,Deck)
Sum = 0
while (Deck has more cards) {
Pick a card X from Deck
Move X to SeenDeck
if (X.Gender == gen) {
Sum = Sum + X.fld
}
}
return(Sum)
end SumMarks- Third parameter
Deck: the loop now runs over the given deck. - New variable
SeenDeckplays the role of the second pile. Deckis modified as the procedure executes: cards move fromDecktoSeenDeck.- At the end
Deckis empty! The procedure should also restoreDeckfromSeenDeck.
The version that restores the deck adds one line before the return:
Procedure SumMarks(gen,fld,Deck)
Sum = 0
while (Deck has more cards) {
Pick a card X from Deck
Move X to SeenDeck
if (X.Gender == gen) {
Sum = Sum + X.fld
}
}
Restore Deck from SeenDeck
return(Sum)
end SumMarksThe lecture asks what the status of Deck is after the procedure. Each card should be the same as before. But is the sequence of cards the same? Perhaps not. It depends what we mean by "restore": SeenDeck would normally be in reverse order.
5.2Side effects
A side effect is when a procedure modifies some data during its computation.
Here the sequence of cards may be disturbed. Does it matter? It depends:
- Not important: adding marks does not depend on how the cards are arranged.
- The side effect is the goal: a procedure to arrange cards in decreasing order of Total Marks exists to change the order.
- Could be undesirable: we pass a deck in decreasing order of Total Marks; afterwards it is randomly rearranged.
- Not tolerated: pronoun matching:
FindMatchmust leave the words and their positions untouched.
5.3Interface versus implementation
Each procedure comes with a contract.
The contract specifies the interface. We can change the procedure's implementation (its code) provided the interface is unaffected.
5.4Side effects in text: pronoun matching
Another task: associating personal pronouns with nouns in a passage of text. Fix a pronoun, search the text before the pronoun backwards, and stop at the nearest name. Write it as a procedure FindMatch(before, pronoun, after): the text before the pronoun, the pronoun, and the text after it.
FindMatch should not disturb before and after: the sequence of words and their positions must stay as they are. No side effects should happen, unlike the card deck where some change was acceptable.5.5Going deeper
- Order matters only sometimes. A sum is the same in any order, but a "first match" or a sorted list is not. Ask whether the answer depends on order before you accept a reordering side effect (extra).
- Write the side effect in the contract. "The deck is reversed" is fine if it is promised and predictable.
- Interface changes break callers. Adding a parameter or changing a promised side effect breaks every call that depends on the old contract.
5.6Exam tips and common mistakes
- For a side-effect question, ask three things: what data changes, does the order matter to the caller, and does the contract promise it?
- When asked "may we change the code?", check the interface first: parameters, return value, side effects.
- Forgetting to restore the deck after the loop (the deck is left empty).
- Assuming the restored deck has the same order as before.
- Changing the interface and thinking it is just a code change.
Practice questions (graded-assignment style)
Numerical Answer Type (NAT).
In the trace of SumMarks(F,Chemistry,Deck), how many cards are left in Deck after card 3 has been moved?
8 cards, 3 moved.
8 - 3 = 5cards remain;SeenDeckis 3, 2, 1 from top to bottom.- Answer: 5
Multiple Choice Question (MCQ): choose the one correct option.
After the loop, the cards in SeenDeck from top to bottom are:
Each new card goes on top of the previous ones.
- The last card moved (8) ends on top, so the order is reversed: 8, 7, ..., 1.
- Answer: option 2.
Multiple Select Question (MSQ): select all that apply.
Which side effects are acceptable?
SumMarks returns the deck in reverse orderFindMatch changes the order of wordsFindMatch only reads the wordsDoes the order matter to the caller?
- Options 1 and 2 are fine (order is irrelevant for a sum; reordering is the goal of a sort). Option 3 is forbidden; option 4 has no side effect at all.
- Answer: options 1, 2 and 4.
Multiple Select Question (MSQ): select all that apply.
Which changes to SumMarks keep the interface unchanged?
Sum to TotalInterface = parameters, return value, side effects.
- Options 1 and 2 change only the implementation. Options 3 and 4 change the interface.
- Answer: options 1 and 2.
Multiple Choice Question (MCQ): choose the one correct option.
For the pronoun He in "Swaminathan was reluctant to open his eyes. He considered ...", FindMatch returns:
Search backwards for the nearest name.
- eyes is not a name and his is a pronoun; the nearest name is Swaminathan.
- Answer: option 4.
Multiple Choice Question (MCQ): choose the one correct option.
Which is part of a procedure's contract?
Functionality plus data integrity.
- The contract fixes the interface: what goes in, what comes out, and what data may change.
- Answer: option 2.
SeenDeck as second pile
Deck empty, then restore
Order of cards may change
SeenDeck is in reverse
Sorting: it is the goal
Pronoun matching: never
Data integrity
Specifies the interface
Keep the interface
Week 3 Summary Sheet
One page to revise all of Week 3: tables, procedures with parameters, using procedures, the three prizes and side effects.
The big picture
- Each attribute is a column, each card is a row.
- Variable-size entries split into tables linked by a unique Id.
- A procedure is a template; arguments (
gen,fld) get the parameters of the call. - Call as an expression, or as a statement if nothing is returned.
Maxmarks(fld)finds the max of any field.- Four calls, four saved values, then compare
MaxTotalwithSubjTotal.
- Keep three maxima and their ids.
TopThreeMarksandSubjectTopperare the natural procedures; plan for same-gender winners and ties.
- Passing a
Deckchanges it; a side effect is data modified by a procedure. - The contract (interface) lists parameters, return value and side effects.
- Read the contract.
- Change the code inside freely, never the promises.
Parts of procedures and calls
| Part | Example | Meaning |
|---|---|---|
| Heading | Procedure SumMarks(gen,fld) | Names the procedure and its arguments |
| Argument | gen, fld | Variables that receive values when the call starts |
| Parameter | F, Chemistry | The values given in the call, copied into the arguments |
| Return | return(Sum) | Hands a value back to the caller |
| End | end SumMarks | Closes the procedure |
| Call as expression | GirlChemSum = SumMarks(F,Chemistry) | Use the returned value, usually assign it |
| Call as statement | UpdateMarks(17,Physics,88) | Nothing useful comes back |
| Boolean call | if (SubjectTopper(X,maths3,phys3,chem3)) | A procedure returning True or False can be the condition itself |
The procedures of this week
| Procedure | Arguments | Returns | Notes |
|---|---|---|---|
SumMaths | gen | Sum | Sum of Maths marks for one gender |
SumPhysics | gen | Sum | Same, with X.Physics |
SumMarks | gen, fld | Sum | Gender and field are parameters |
UpdateMarks | CardId, Subject, Marks | nothing useful | Called as a statement |
Maxmarks | fld | Maxval | Maximum of any field |
TopThreeMarks | Subj | thirdmax | Third highest mark in a subject |
SubjectTopper | Card, MMark, PMark, CMark | True / False | Top three in at least one subject |
SumMarks (with a deck) | gen, fld, Deck | Sum | Moves cards to SeenDeck and restores Deck; order may change |
FindMatch | before, pronoun, after | the match for the pronoun | No side effects allowed |
The slot update to remember
if (X.Total > max) {
thirdmax = secondmax
thirdmaxid = secondmaxid
secondmax = max
secondmaxid = maxid
max = X.Total
maxid = X.Id
}Which tool when?
| Situation | Tool |
|---|---|
| Cards with a fixed set of attributes | One table: attribute = column, card = row |
| Entries vary in number, such as a bill | Two tables linked by a unique Id |
| Same loop with a small change | A procedure with parameters |
| A value is needed back | return(...), then assign: x = Proc(...) |
| Nothing useful to return | A call used as a separate statement |
| Top three of something, and who | Three slots plus three ids, strict > |
| Who is eligible? | A Boolean procedure: if (Proc(...)) |
| Does the procedure change its data? | State it in the contract (interface) |
Common mistakes
- A call like
SumMarks(F,Total)on its own line throws the answer away. Assign it.
- The argument is the name in the heading; the parameter is the value in the call.
- Set
maxid,secondmaxid,thirdmaxidto -1 before the loop, like the maxima to 0.
- After a loop over
Deck, it is empty. Restore it fromSeenDeck, and remember the order may differ.
- Adding a parameter or changing a promised side effect breaks every caller.
- Id, Shop, Customer and Total get copied into every row. Use two linked tables.
- Strict comparisons ignore equal marks:
90, 90, 90leavesthirdmax = 0. Decide a tie rule first.