Quiz 2

Week 2: Iteration & Filtering

2188 words
11 min read
Python Week 1: the first filter for runtime behavior
Visual companion
Python
Type and operator map

Python Week 1: the first filter for runtime behavior

View
Revision summary

What this note is really saying

Short form

# Week 2: Iteration & Filtering > **BSCS1001 — IIT Madras BS Degree** **Prerequisite:** Topic 03 (Pseudocode Basics) **Cross-links:** BSCS1002-Python (Week 2 — Loops, Conditions) ## 1. Motivation: Beyond Simple Counting In Topic 01, we learned that iteration means "doing something repeatedly." But what exactly can w...

Week 2: Iteration & Filtering

BSCS1001 — IIT Madras BS Degree Prerequisite: Topic 03 (Pseudocode Basics) Cross-links: BSCS1002-Python (Week 2 — Loops, Conditions)

1. Motivation: Beyond Simple Counting

In Topic 01, we learned that iteration means "doing something repeatedly." But what exactly can we do repeatedly? Three fundamental operations form the backbone of almost every algorithm:
OperationDescriptionAnalogy
CountHow many items?Counting students in a class
SumAdd up valuesTotal marks of all students
Max/MinFind extreme valuesWho scored highest?
These may seem simple, but they are the building blocks of sophisticated data analysis.
💡 Key Insight: The difference between counting, summing, and finding max is just what you do inside the loop. The iteration structure is the same.

2. The Two Core Patterns

Pattern A: Accumulation (Count, Sum)

In accumulation, the variable's new value depends on its previous value plus something new.
pseudo
Variable = Variable + NewValue
Examples:
  • Count = Count + 1 (add 1 each time)
  • Sum = Sum + X.Maths (add current value each time)

Pattern B: Tracking (Max, Min)

In tracking, the variable's new value might be replaced if the current item is more extreme.
pseudo
if (X.Value > Variable) {
    Variable = X.Value
}
Examples:
  • if (X.Maths > Max) { Max = X.Maths } (update max)
  • if (X.Maths < Min) { Min = X.Maths } (update min) (Diagram)

3. Finding Maximum: The Tracker Pattern

The Algorithm

sql
Max = 0
while (Pile 1 has more cards) {
    Pick a card X from Pile 1
    Move X to Pile 2
    if (X.Maths > Max) {
        Max = X.Maths
    }
}

How It Works

  1. Initialize Max to a very small value (0 if marks are non-negative)
  2. For each card, compare X.Maths with current Max
  3. If X.Maths is larger, update Max
  4. After processing all cards, Max holds the largest value

Flowchart

(Diagram)

Tracing: Find Maximum Marks

Dataset: [45, 78, 62, 91, 53]
IterX.MathsMax BeforeCondition (X > Max?)Max After
145045 > 0 ✅ Yes45
2784578 > 45 ✅ Yes78
3627862 > 78 ❌ No78
4917891 > 78 ✅ Yes91
5539153 > 91 ❌ No91
Result: Maximum = 91

What If All Values Are Negative?

If Max = 0 but all marks are negative (e.g., [-5, -10, -3]), the algorithm incorrectly returns 0. Solution: Initialize Max to the first card's value instead:
sql
Max = 0
FirstCard = True
while (Pile 1 has more cards) {
    Pick a card X from Pile 1
    Move X to Pile 2
    if (FirstCard) {
        Max = X.Maths
        FirstCard = False
    }
    else if (X.Maths > Max) {
        Max = X.Maths
    }
}

4. Finding Max with Card ID

Often we need to know which student has the max marks, not just the value.

The Algorithm

sql
MaxM = 0
MaxCard = -1
while (Pile 1 has more cards) {
    Pick a card X from Pile 1
    Move X to Pile 2
    if (X.Maths > MaxM) {
        MaxM = X.Maths
        MaxCard = X.Id
    }
}

Tracing

Dataset:
Card IDNameMaths
101Alice85
102Bob92
103Charlie78
104Diana95
IterX.IdX.MathsMaxM BeforeConditionMaxM AfterMaxCard
110185085>0 ✅85101
2102928592>85 ✅92102
3103789278>92 ❌92102
4104959295>92 ✅95104
Result: Max = 95, achieved by student ID = 104 (Diana)

Why Initialize MaxCard to -1?

  • Card IDs are typically positive numbers (e.g., 1, 2, 3, ...)
  • -1 is an impossible card ID, serving as "no card selected yet"
  • If MaxCard remains -1 after the loop, the dataset was empty

5. Finding Both Max and Min

We can find both in a single pass:
sql
Max = -INFINITY
Min = INFINITY
while (Pile 1 has more cards) {
    Pick a card X from Pile 1
    Move X to Pile 2
    if (X.Maths > Max) {
        Max = X.Maths
    }
    if (X.Maths < Min) {
        Min = X.Maths
    }
}

Tracing

Dataset: [45, 78, 62, 91, 53]
IterXMax BeforeMax AfterMin BeforeMin After
145-∞4545
27845784545
36278784545
49178914545
55391914553? No, 45 < 53 so Min stays 45
Result: Max = 91, Min = 45
Note: Two separate if statements (not if-else) because a single card could be both new max AND new min (if it's the first card).

6. The AND Operator in Filters

Compound Conditions

The AND operator combines two conditions — both must be True for the combined condition to be True.

AND Truth Table

Condition 1Condition 2C1 AND C2
FalseFalseFalse
FalseTrueFalse
TrueFalseFalse
TrueTrueTrue

Using AND in Filtering

sql
Count = 0
while (Pile 1 has more cards) {
    Pick a card X from Pile 1
    Move X to Pile 2
    if (X.Gender == "M" AND X.Maths > 80) {
        Count = Count + 1
    }
}
This counts boys who scored above 80 in Maths.

Worked Example: AND Filter

Dataset:
NameGenderMaths
AliceF90
BobM85
CharlieM72
DianaF78
EthanM95
Filter: X.Gender == "M" AND X.Maths > 80
CardGenderMathsGender=="M"?Maths>80?ANDIncrement?
AliceF90NoYesNo
BobM85YesYesYes✅ Count=1
CharlieM72YesNoNo
DianaF78NoNoNo
EthanM95YesYesYes✅ Count=2
Result: Count = 2 (Bob and Ethan)

Comparison: AND vs Sequential Ifs

(Diagram) Both forms are equivalent. AND is more compact.

7. Accumulation through Iteration

Accumulation is the process of building up a value step by step during iteration.

Types of Accumulators

AccumulatorInitial ValueUpdate RuleExample
Counter0Count = Count + 1Number of students
Sum0Sum = Sum + X.ValueTotal marks
Product1Prod = Prod × X.Value(Rare in this course)
List builder[]List = List ++ [X]Collecting items (Week 5)

Combining Accumulation with Filtering

We can accumulate while filtering:
sql
TotalBoysMaths = 0
while (Pile 1 has more cards) {
    Pick a card X from Pile 1
    Move X to Pile 2
    if (X.Gender == "M") {
        TotalBoysMaths = TotalBoysMaths + X.Maths
    }
}
This is accumulation with filtering — one of the most common patterns in the course.

Multiple Accumulators

We can track multiple things in a single pass:
sql
BoySum = 0
GirlSum = 0
BoyCount = 0
GirlCount = 0
while (Pile 1 has more cards) {
    Pick a card X from Pile 1
    Move X to Pile 2
    if (X.Gender == "M") {
        BoySum = BoySum + X.Maths
        BoyCount = BoyCount + 1
    }
    else {
        GirlSum = GirlSum + X.Maths
        GirlCount = GirlCount + 1
    }
}
BoyAvg = BoySum / BoyCount
GirlAvg = GirlSum / GirlCount
This computes the average Maths marks for boys and girls separately in a single pass!

8. Comparison: Iteration Patterns

Summary Table

PatternInitial ValueUpdate ConditionUpdate ActionUse Case
Count0Always (every card)Count = Count + 1How many?
Sum0Always (or with filter)Sum = Sum + X.ValueTotal?
AverageSum=0, Count=0AlwaysSum+=X, Count+=1What's typical?
Max0 or -∞When X > MaxMax = X.ValueBest score?
MinWhen X < MinMin = X.ValueWorst score?
Max with IDMax=0, ID=-1When X > MaxMax = X.Value; ID = X.IdWho scored best?

Decision Tree: Which Pattern?

(Diagram)

9. Practice Questions

Basic Questions

Q1. Trace the max-finding algorithm for dataset [12, 45, 7, 38, 22].
Show Answer
IterXMax BeforeX > Max?Max After
112012>0 ✅12
2451245>12 ✅45
37457>45 ❌45
4384538>45 ❌45
5224522>45 ❌45
Max = 45 Q2. What does this pseudocode output for dataset [3, 8, 1, 6]?
sql
Result = 0
while (Pile 1 has more cards) {
    Pick a card X from Pile 1
    Move X to Pile 2
    if (X > Result) {
        Result = X
    }
}
Show Answer
IterXX > Result?Result
133 > 0 ✅3
288 > 3 ✅8
311 > 8 ❌8
466 > 8 ❌8
Result = 8 (the maximum) Q3. Write pseudocode to find the minimum value (instead of maximum). Show Answer
sql
Min = INFINITY   // A very large number
while (Pile 1 has more cards) {
    Pick a card X from Pile 1
    Move X to Pile 2
    if (X < Min) {
        Min = X
    }
}
Q4. Evaluate these AND conditions: (a) True AND False (b) True AND True (c) False AND False (d) (5 > 3) AND (10 < 20)
Show Answer
ExpressionStep 1Step 2Result
True AND FalseFalse
True AND TrueTrue
False AND FalseFalse
(5>3) AND (10<20)True AND TrueTrue

Intermediate Questions

Q5. Write pseudocode to find the student with the minimum marks in Physics (return both the marks and the student ID).
Show Answer
sql
MinPhy = INFINITY
MinCard = -1
while (Pile 1 has more cards) {
    Pick a card X from Pile 1
    Move X to Pile 2
    if (X.Physics < MinPhy) {
        MinPhy = X.Physics
        MinCard = X.Id
    }
}
Q6. What is the difference between these two code snippets? Snippet A:
pseudo
if (X.Gender == "M") {
    if (X.Maths > 80) {
        Count = Count + 1
    }
}
Snippet B:
pseudo
if (X.Gender == "M" AND X.Maths > 80) {
    Count = Count + 1
}
Show Answer
They are equivalent. Both count boys who scored above 80. Snippet A uses nested if statements, Snippet B uses a compound condition with AND. The result is identical. Q7. Trace this pseudocode. What does it compute?
sql
Result = 0
Count = 0
while (Pile 1 has more cards) {
    Pick a card X from Pile 1
    Move X to Pile 2
    if (X > 0) {
        Result = Result + X
        Count = Count + 1
    }
}
Result = Result / Count
For dataset: [-5, 10, 0, 20, -3, 15]
Show Answer
IterXX > 0?ResultCount
1-500
210101
30❌ (not >0)101
420302
5-3302
615453
Final: Result = 45 / 3 = **15**
It computes the average of positive numbers. Q8. The following algorithm has a bug. Find and fix it.
sql
Max = 0
while (Pile 1 has more cards) {
    Pick a card X from Pile 1
    Move X to Pile 2
    if (Max > X.Maths) {
        Max = X.Maths
    }
}
Show Answer
Bug: The condition is reversed! if (Max > X.Maths) updates Max when the current Max is greater than X.Maths, which would track the minimum, not the maximum.
Fix: Change to if (X.Maths > Max).
Also, if all values could be negative, initialize Max to the first value or -INFINITY.

Advanced Questions

Q9. Write pseudocode to find the second highest value in a dataset.
Show Answer
sql
Max = 0
SecondMax = 0
while (Pile 1 has more cards) {
    Pick a card X from Pile 1
    Move X to Pile 2
    if (X > Max) {
        SecondMax = Max
        Max = X
    }
    else if (X > SecondMax) {
        SecondMax = X
    }
}
Logic:
  • When we find a new maximum, the old maximum becomes the second maximum
  • Otherwise, check if X beats the current second maximum Q10. Trace the second-max algorithm for dataset [10, 30, 20, 50, 40]. Show Answer
IterXBefore: Max, SecMaxActionAfter: Max, SecMax
1100, 0X > Max → SecMax=0, Max=1010, 0
23010, 0X > Max → SecMax=10, Max=3030, 10
32030, 10X not > Max, X > SecMax (20>10) → SecMax=2030, 20
45030, 20X > Max → SecMax=30, Max=5050, 30
54050, 30X not > Max, X > SecMax (40>30) → SecMax=4050, 40
Result: Max = 50, SecondMax = 40 Q11. Write pseudocode that counts how many times each of the values "High", "Medium", "Low" appears in a dataset (but without using dictionaries — just three counters). Show Answer
sql
HighCount = 0
MedCount = 0
LowCount = 0
while (Pile 1 has more cards) {
    Pick a card X from Pile 1
    Move X to Pile 2
    if (X.Category == "High") {
        HighCount = HighCount + 1
    }
    else if (X.Category == "Medium") {
        MedCount = MedCount + 1
    }
    else if (X.Category == "Low") {
        LowCount = LowCount + 1
    }
}
Q12. Design an algorithm that finds both the maximum Maths mark AND which gender achieved it. You need to track the maximum and the gender of the student who achieved it.
Show Answer
sql
MaxM = -1
MaxGender = ""
while (Pile 1 has more cards) {
    Pick a card X from Pile 1
    Move X to Pile 2
    if (X.Maths > MaxM) {
        MaxM = X.Maths
        MaxGender = X.Gender
    }
}
// Now MaxGender tells us if a boy or girl topped Maths
Trace with data:
CardGenderMathsActionMaxMMaxGender
1F85New max85F
2M92New max92M
3M78No92M
4F95New max95F
Result: Max = 95, achieved by a Female student.

📚 Cross-References

CourseTopicConnection
BSCS1002 (Python)Week 2 — LoopsPython for and while loops
BSCS1002 (Python)Week 3 — ConditionsPython if, elif, else
BSCS2002 (PDSA)Week 2 — Max/MinFormal algorithm analysis

Quiz Tip: Single-iteration max/min problems are the most common type in Quiz 1. Practice tracing until it's automatic! Join Discord PreviousPseudocode BasicsNextProcedures & Parameters
Document outline

Keep your place and jump directly to a heading.

Table of Contents
System Normal // Awaiting Context

Intelligence Hub

Navigate the knowledge graph to generate context. The Hub adapts dynamically to surface backlinks, related notes, and metadata insights.