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:

  1. Draw Table: Columns for A, B, Input.
  2. Step-by-Step: Update values row by row.
  3. Final Row: That’s your answer.

Pattern 1.2: Swap

Question: “Swap A and B.” Algorithm:

  1. T = A
  2. A = B
  3. B = T

Week 3: Conditionals

Pattern 3.1: Nested If (AND)

Question: “When does X=1?” Code: If A: If B: X=1 Algorithm:

  1. 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:

  1. If Score is 95, it prints A.
  2. It skips B (even though 95 > 80).

Week 4-5: Loops

Pattern 4.1: Counter vs Accumulator

Question: “What does variable X do?” Algorithm:

  1. Look at the update line.
  2. X = X + 1 Counter (Counts items).
  3. X = X + Val Accumulator (Sums values).

Pattern 4.2: Infinite Loop Check

Question: “Does it stop?” Algorithm:

  1. Check the condition (e.g., i < 10).
  2. Check the update (e.g., i = i - 1).
  3. If i moves away from the target (10), it’s infinite.

Pattern 5.1: Nested Loop Count

Question: “How many times does inner body run?” Algorithm:

  1. Count Outer iterations ().
  2. Count Inner iterations ().
  3. 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:

  1. 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:

  1. Starts False.
  2. If any item is 5, turns True.
  3. 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] = 1

Algorithm:

  1. New Item: Start count at 1.
  2. 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:

  1. Key: The category (City).
  2. Value: A List of items (Students).

Week 8: Procedures

Pattern 8.1: Modular Logic

Question: “What does Procedure X do?” Algorithm:

  1. Treat the Procedure as a Black Box.
  2. Input [Procedure] Output.
  3. 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:

  1. It usually transforms a List into a Dictionary (e.g., Frequency count or Grouping).