Week 2: Iteration, Filtering & Selection

3508 words
18 min read
2026-09-12T00:00:00.000Z
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

Iterating over datasets, tracking state, accumulator patterns, finding maximum/minimum values, and the AND operator. # Computational Thinking — Week 2: Iteration, Filtering & Selection IITM’s CT Week 2 covers **Iteration, Filtering, Selection, Pseudocode, Finding Maximum and Minimum, and the AND operator**.

Computational Thinking — Week 2: Iteration, Filtering & Selection

IITM’s CT Week 2 covers Iteration, Filtering, Selection, Pseudocode, Finding Maximum and Minimum, and the AND operator.

TL;DR

Week 1 gave the basic loop structure.
Week 2 adds decision-making inside loops.
The core pattern becomes:
text
initialize state

for each item:
    check conditions
    selectively update state

output result
The highest-value ideas are:
  • iteration = repeatedly process data
  • filtering = decide which items matter
  • selection = choose what action to take based on conditions
  • pseudocode = language-independent algorithm description
  • maximum/minimum = keep track of the best value seen so far
  • AND = multiple conditions must all be true

1. Iteration recap

Iteration means repeatedly executing the same logical steps.
Example:
text
for each x in data:
    process x
If:
text
data = [4, 7, 2]
then the body executes three times.

2. Iteration over a dataset

Suppose:
text
marks = [45, 72, 88, 39]
A loop conceptually behaves like:
text
x = 45
x = 72
x = 88
x = 39
one after another.

3. State during iteration

An algorithm usually maintains some state.
Example:
text
count = 0
Then while scanning the data:
text
count = count + 1
when required.
The current state summarizes what has happened so far.

4. Filtering

Filtering means:
process only the items satisfying a condition.
Example:
text
for each x:
    if x > 50:
        process x
All other values are ignored.

5. Example

Data:
text
20, 60, 75, 30, 90
Filter:
text
x > 50
Selected values:
text
60, 75, 90

6. Filter + count

Suppose we want:
number of students with marks above 50.
Pseudocode:
text
count = 0

for each mark:
    if mark > 50:
        count = count + 1
For:
text
20, 60, 75, 30, 90
output:
3\boxed{3}

7. Filter + sum

Suppose we want:
sum of only positive values.
text
total = 0

for each x:
    if x > 0:
        total = total + x
For:
text
-3, 5, 7, -1
output:
5+7=12.5+7=12.

8. Selection

Selection means choosing between different actions based on conditions.
Basic form:
text
if condition:
    action A
else:
    action B
So iteration answers:
repeat?
Selection answers:
which branch?

9. Example

text
if mark >= 40:
    result = "Pass"
else:
    result = "Fail"
Only one branch executes.

10. Multiple-way selection

Sometimes there are several cases.
Example:
text
if mark >= 90:
    grade = "A"
else if mark >= 75:
    grade = "B"
else if mark >= 60:
    grade = "C"
else:
    grade = "D"
The order of conditions matters.

11. Why order matters

Suppose:
text
mark = 95
If you test:
text
mark >= 60
first and stop there, you might incorrectly classify it as just the lowest passing grade.
So selection logic should usually test more specific/higher-priority cases first.

12. Iteration + selection

Most real algorithms combine both.
Example:
text
count = 0

for each mark:
    if mark >= 50:
        count = count + 1
Loop:
  • visits every mark
Selection:
  • decides whether to increment

13. Pseudocode

Pseudocode describes an algorithm without committing to a specific programming language.
Example:
text
total = 0

for each number x in data:
    total = total + x

print total
The goal is logic, not syntax.

14. Why pseudocode is useful

It lets you focus on:
  • state
  • conditions
  • iteration
  • sequence
  • correctness
without worrying about:
  • Python syntax
  • semicolons
  • indentation rules of a specific language
  • libraries

15. Reading pseudocode

You should read pseudocode literally and sequentially.
Example:
text
x = 5
x = x + 2
x = x * 3
Trace:
5→7→21.5 \rightarrow 7 \rightarrow 21.
Final:
21\boxed{21}

16. Trace tables

A trace table is one of the best tools in CT.
Example:
text
s = 0

for each x in [2, 4, 1]:
    s = s + x
Stepxs befores after
start——0
1202
2426
3167
Final:
s=7\boxed{s=7}

17. Finding a maximum

Suppose we have:
text
4, 9, 2, 11, 6
We want the largest value.
A standard pattern is:
text
max = first value

for each remaining value x:
    if x > max:
        max = x

18. Maximum trace

Data:
text
4, 9, 2, 11, 6
Initialize:
text
max = 4
Then:
xCurrent maxx > max?New max
94Yes9
29No9
119Yes11
611No11
Final:
11\boxed{11}

19. Maximum invariant

During the loop:
max is the largest value among all items processed so far.
That is the key mental model.

20. Finding a minimum

Same idea:
text
min = first value

for each remaining value x:
    if x < min:
        min = x

21. Minimum example

Data:
text
8, 5, 12, 3, 9
Trace:
text
min = 8
then:
8→5→5→3→3.8\to5\to5\to3\to3.
Final:
3\boxed{3}

22. Why initialize max/min to first value

This is safer than using arbitrary values.
Suppose all numbers are negative:
text
-10, -5, -20
If you initialize:
text
max = 0
then algorithm may wrongly return:
00
even though 00 is not in the data.
Correct:
text
max = first value

23. Bad maximum initialization

Wrong:
text
max = 0
for arbitrary numerical data.
Example:
text
[-8, -2, -15]
Nothing exceeds:
text
0
so algorithm incorrectly keeps:
0.0.

24. Alternative extreme sentinel

Sometimes algorithms use conceptual values such as:
text
max = -infinity
min = +infinity
Then every real input can update appropriately.
But for manual CT problems, using the first valid observation is often cleaner.

25. Finding max among filtered data

Suppose:
Find the largest even number.
Now two conditions are involved:
  1. value must be even
  2. among eligible values, find largest
Conceptually:
text
for each x:
    if x is even:
        compare x with current maximum
Filtering happens before max comparison.

26. Careful initialization with filters

Suppose:
text
data = [3, 8, 5, 12]
and we want maximum even value.
You cannot simply initialize:
text
max_even = first value
because first value:
text
3
is not even.
Instead initialize from the first qualifying value, or maintain a flag indicating whether one has been found.

27. Flag pattern

Example:
text
found = False

for each x:
    if x is even:
        if found == False:
            max_even = x
            found = True
        else if x > max_even:
            max_even = x
This handles cases where qualifying values may appear later.

28. Why this matters

What if data are:
text
3, 5, 7
and you ask for maximum even value?
There is no valid answer from the dataset.
A proper algorithm should detect:
text
found = False
at the end.

29. AND operator

The logical AND combines conditions.
Expression:
text
A AND B
is true only if:
  • A is true
  • B is true

30. AND truth table

ABA AND B
FalseFalseFalse
FalseTrueFalse
TrueFalseFalse
TrueTrueTrue
So:
A∧B\boxed{ A\land B }
requires both.

31. Example

Condition:
text
age >= 18 AND age <= 60
means age must satisfy:
18≤age≤60.18\leq age\leq60.
Both boundaries must hold.

32. Range filtering with AND

Suppose we want numbers strictly between 10 and 20:
text
x > 10 AND x < 20
This selects:
text
11, 12, ..., 19
if integers are involved.

33. Example

For:
text
x = 15
we have:
text
15 > 10  → True
15 < 20  → True
Therefore:
text
True AND True → True

34. Another example

For:
text
x = 25
text
25 > 10 → True
25 < 20 → False
Then:
text
True AND False → False
So it is filtered out.

35. AND with multiple criteria

Example:
Count students who scored above 60 and attended at least 75%.
Condition:
text
marks > 60 AND attendance >= 75
Both must be satisfied.

36. Example table

StudentMarksAttendanceSelected?
A8090Yes
B8060No
C5090No
D7080Yes
Only A and D satisfy both.

37. AND vs nested conditions

These are often equivalent:
text
if A AND B:
    action
and:
text
if A:
    if B:
        action
Both require A and B.

38. But structure can matter

Consider:
text
if A:
    action1
    if B:
        action2
Now:
  • action1 requires only A
  • action2 requires A and B
So do not mechanically merge every nested condition.

39. Short-circuit intuition

In many programming systems:
text
A AND B
may stop checking once A is false.
Why?
Because:
text
False AND anything
must be false.
This is called short-circuit evaluation.
Useful conceptually, though exact pseudocode semantics depend on the course notation.

40. Combining filtering and AND

Suppose:
Sum values between 5 and 10 inclusive.
Pseudocode:
text
total = 0

for each x:
    if x >= 5 AND x <= 10:
        total = total + x

41. Example

Data:
text
3, 5, 7, 11, 10
Selected:
text
5, 7, 10
Sum:
5+7+10=22.5+7+10=22.

42. Finding maximum with AND

Suppose each record has:
  • age
  • salary
Question:
Find maximum salary among people aged 20–30.
Filter:
text
age >= 20 AND age <= 30
Then among only those records:
text
compare salary with max
This is a common multi-stage CT pattern.

43. Selection can update different variables

Example:
text
positive = 0
negative = 0

for each x:
    if x > 0:
        positive = positive + 1
    else:
        negative = negative + 1
One condition decides which state variable changes.

44. Partitioning data

A selection can divide a dataset into categories.
Example:
text
if x < 0:
    negative
else if x == 0:
    zero
else:
    positive
Every number belongs to exactly one category.

45. Exhaustive selection

A set of conditions is exhaustive if every possible input matches some branch.
Example:
text
if x > 0:
    ...
else if x == 0:
    ...
else:
    ...
covers every real number.

46. Mutually exclusive branches

Branches are mutually exclusive when an item cannot satisfy more than one selected branch in the same decision chain.
Example:
text
if x < 0
else if x == 0
else
Only one branch executes.

47. Independent ifs vs if/else

Compare:
text
if x > 0:
    A

if x > 10:
    B
For:
x=20,x=20,
both A and B happen.
But:
text
if x > 0:
    A
else if x > 10:
    B
For:
x=20,x=20,
only A happens because first condition already matched.
This distinction is important.

48. Selection order trap

Consider:
text
if marks >= 40:
    grade = "Pass"
else if marks >= 90:
    grade = "Excellent"
For:
95,95,
the first condition is already true.
So "Excellent" is never reached.
Correct ordering would put the more specific condition first.

49. Maximum and minimum together

You can compute both in one pass:
text
max = first value
min = first value

for each remaining x:
    if x > max:
        max = x

    if x < min:
        min = x
Time-wise, one traversal is enough.

50. Example

Data:
text
7, 2, 10, 4
Start:
text
min = 7
max = 7
After full scan:
min⁡=2,max⁡=10\boxed{ \min=2,\quad\max=10 }

51. Range from min/max

Once min and max are known:
range=max⁡−min⁡\boxed{ \text{range} = \max-\min }
So CT algorithms can directly implement statistical summaries from Stats Week 3.

52. Counting max occurrences

Suppose we want:
maximum value and how often it occurs.
A useful pattern:
text
max = first value
count = 1

for each remaining x:
    if x > max:
        max = x
        count = 1
    else if x == max:
        count = count + 1

53. Why reset count?

Suppose current maximum is:
55
and it occurred three times.
Then we encounter:
9.9.
All previous counts of 55 are irrelevant because 55 is no longer the maximum.
So:
text
count = 1
for the newly discovered maximum.

54. Example trace

Data:
text
3, 5, 5, 2, 8, 8, 8
Progress:
text
max=3, count=1
max=5, count=1
max=5, count=2
max=5, count=2
max=8, count=1
max=8, count=2
max=8, count=3
Final:
max⁡=8,count=3\boxed{ \max=8,\quad count=3 }
Common mistake:
AND vs OR
Suppose requirement is:
age is between 18 and 60.
Correct:
text
age >= 18 AND age <= 60
Using OR:
text
age >= 18 OR age <= 60
is true for almost every real age.
For example:
age=100age=100
satisfies:
text
age >= 18
so entire OR becomes true.

Common mistake: impossible AND
Condition:
text
x < 5 AND x > 10
can never be true.
No number is simultaneously:
<5<5
and:
>10.>10.
Always inspect whether combined constraints are compatible.

Common mistake: using first data item despite filtering
If the task is:
maximum among positive values,
and first value is negative, initializing max to the first value can produce awkward logic.
Initialize using the first valid filtered item or use a flag.

Common mistake: resetting maximum inside loop
Wrong:
text
for each x:
    max = first_value
    if x > max:
        max = x
This repeatedly discards progress.
Initialization should usually happen once, before the loop.

Common mistake: update max in wrong direction
To find maximum:
text
if x > max
not:
text
if x < max
The second pattern finds minimum-like behavior.

Common mistake: output current item instead of state
Suppose the loop ends on:
text
x = 6
while:
text
max = 11.
If asked for maximum, output:
text
max
not the iterator:
text
x

Common mistake: confuse filtering with stopping
text
if x < 0:
    ignore x
does not normally mean:
terminate the entire loop.
It means:
do not process this particular item further.
Filtering and termination are different.

Common mistake: infer values instead of tracing
If pseudocode says:
text
A = A + 2
then A increases by 2.
Even if you think it "should" count items by 1, do not repair the algorithm while solving a tracing question.

63. Core pattern: counting with two conditions

text
count = 0

for each record:
    if condition1 AND condition2:
        count = count + 1
This pattern appears everywhere.
Example:
  • female AND age > 50
  • marks > 60 AND attendance > 75
  • price < 1000 AND rating >= 4

64. Core pattern: maximum

text
max = first valid item

for each remaining valid item x:
    if x > max:
        max = x
Remember:
max so far\boxed{ \text{max so far} }

65. Core pattern: minimum

text
min = first valid item

for each remaining valid item x:
    if x < min:
        min = x
Remember:
min so far\boxed{ \text{min so far} }

66. Core pattern: classify

text
for each x:
    if condition A:
        category_A = category_A + 1
    else:
        category_B = category_B + 1
This partitions data into groups.

67. Core pattern: range filter

text
if lower <= x AND x <= upper:
    process x
Mathematically:
lower≤x≤upper\boxed{ lower\leq x\leq upper }

68. Trace example

Consider:
text
A = 0
B = 0

for each x in [4, 9, 12, 3, 15]:
    if x > 5 AND x < 14:
        A = A + 1
        B = B + x
Trace:
xxx>5x>5x<14x<14ANDAABB
4FTF00
9TTT19
12TTT221
3FTF221
15TFF221
Final:
A=2,B=21\boxed{ A=2,\quad B=21 }

69. Another trace: max

text
M = 6

for each x in [2, 9, 5, 12, 10]:
    if x > M:
        M = x
Progress:
6→6→9→9→12→12.6\to6\to9\to9\to12\to12.
Final:
M=12\boxed{M=12}

70. Week 1 → Week 2 connection

Week 1 gave:
  • variables
  • initialization
  • basic iteration
  • filtering
Week 2 adds:
  • richer conditions
  • selection
  • explicit pseudocode reasoning
  • max/min patterns
  • Boolean conjunction
So the algorithm can now do more than simply traverse data.
It can make decisions and retain the most important observation seen so far.

71. Week 2 mental map

text
DATA
 ↓
Iterate
 ↓
Check condition(s)
 ↓
Selection
 ├── ignore item
 ├── update count/sum
 ├── update maximum
 └── update minimum
 ↓
Continue
 ↓
Final state

72. What you should actually master

By the end of CT Week 2, you should be able to:
  1. Trace an iterative algorithm accurately.
  2. Explain filtering.
  3. Distinguish filtering from selection.
  4. Read and write simple pseudocode.
  5. Use if / else logic.
  6. Understand why branch order matters.
  7. Find maximum in one pass.
  8. Find minimum in one pass.
  9. Initialize max/min safely.
  10. Find max/min among filtered items.
  11. Use the AND operator correctly.
  12. Evaluate combined Boolean conditions.
  13. Distinguish independent ifs from if/else.
  14. Combine filtering with counting or summation.
  15. Build trace tables rather than relying on intuition.
If those are comfortable, Computational Thinking Week 2 is under control.

Quick Recall & Flashcards

Test your active recall before proceeding to practice problems. Format:
Question :: Answer.
  • Week 2 Diagnostic: To find the maximum score in a dataset using a single pass, how should the accumulator variable max_so_far be initialized? :: Answer: A — To find a maximum, initialize max_so_far to the lowest possible value so any real element can replace it on first comparison.
  • Week 2 Diagnostic: If condition A is True and condition B is False, what does (A and B) evaluate to? :: Answer: B — The logical AND operator requires both operands to be True. If either is False, the result is False.

Practice & Self-Check

Attempt these diagnostic questions to verify your operational understanding.
1

Question 1

To find the maximum score in a dataset using a single pass, how should the accumulator variable max_so_far be initialized?
MCQ
3 Unit Assessment
A. To 0 or -infinity (a value less than or equal to any valid score)
B. To the sum of all scores
C. To +infinity
D. To the length of the dataset
2

Question 2

If condition A is True and condition B is False, what does (A and B) evaluate to?
MCQ
3 Unit Assessment
A. True
B. False
C. None
D. Error

Active Recall Session

Document outline

Keep your place and jump directly to a heading.

Table of contents

No note selected

Open a chapter to see its outline, backlinks, and sources here.