CT: Pattern Bank & Mental Algorithms
IMPORTANT
Master List: Every standard logic pattern in CT.
Week 1-2: Basics
Pattern 1.1: The Trace Table
Question: “What is the value of A, B?” Algorithm:
- Draw Table: Columns for A, B, Input.
- Step-by-Step: Update values row by row.
- Final Row: That’s your answer.
Pattern 1.2: Swap
Question: “Swap A and B.” Algorithm:
T = AA = BB = T
Week 3: Conditionals
Pattern 3.1: Nested If (AND)
Question: “When does X=1?”
Code: If A: If B: X=1
Algorithm:
- Equivalent to
If A AND B.
Pattern 3.2: Ladder (First Match)
Question: “Output?”
Code: If Score > 90: A. Else If Score > 80: B.
Algorithm:
- If Score is 95, it prints A.
- It skips B (even though 95 > 80).
Week 4-5: Loops
Pattern 4.1: Counter vs Accumulator
Question: “What does variable X do?” Algorithm:
- Look at the update line.
X = X + 1Counter (Counts items).X = X + ValAccumulator (Sums values).
Pattern 4.2: Infinite Loop Check
Question: “Does it stop?” Algorithm:
- Check the condition (e.g.,
i < 10). - Check the update (e.g.,
i = i - 1). - If
imoves away from the target (10), it’s infinite.
Pattern 5.1: Nested Loop Count
Question: “How many times does inner body run?” Algorithm:
- Count Outer iterations ().
- Count Inner iterations ().
- Total = .
Week 6: Lists
Pattern 6.1: Filtering
Question: “What is in L2?”
Code: For x in L1: If x > 0: L2 = L2 + [x]
Algorithm:
- L2 contains only positive numbers from L1.
Pattern 6.2: Search (Found Flag)
Question: “Does list contain 5?” Code:
Found = False
For x in L:
If x == 5:
Found = True
Algorithm:
- Starts False.
- If any item is 5, turns True.
- Remains True forever after that.
Week 7: Dictionaries
Pattern 7.1: Frequency Count (Histogram)
Question: “Count occurrences of each word.” Code:
If w in D:
D[w] = D[w] + 1
Else:
D[w] = 1Algorithm:
- New Item: Start count at 1.
- Existing Item: Add 1 to current count.
Pattern 7.2: Grouping (Bucketing)
Question: “Group students by City.” Code:
If city in D:
D[city] = D[city] ++ [student]
Else:
D[city] = [student]Algorithm:
- Key: The category (City).
- Value: A List of items (Students).
Week 8: Procedures
Pattern 8.1: Modular Logic
Question: “What does Procedure X do?” Algorithm:
- Treat the Procedure as a Black Box.
- Input [Procedure] Output.
- Trace the main code using the result of the procedure, don’t re-trace the procedure internals every single time if you already know what it does.
Pattern 8.2: Dictionary in Procedure
Question: “What does this return?”
Code: Procedure F(L): D={}; ... return D
Algorithm:
- It usually transforms a List into a Dictionary (e.g., Frequency count or Grouping).