Open In Colab

Module 01: NumPy Fundamentals - Participation Exercises#

Exercise 1.1: Mini-Exercise - Vectorization Challenge#

Type: 🔧 Mini-Exercise (7 min)

Convert this loop-based code to vectorized NumPy operations. Time both versions.

import numpy as np

# Given: temperatures in Celsius
temps_C = np.array([25, 50, 75, 100, 125, 150, 175, 200])

# Loop version (slow) - calculate vapor pressure using Antoine equation
# For water: log10(P) = A - B/(C + T), with A=8.07, B=1730.63, C=233.43
A, B, C = 8.07, 1730.63, 233.43

pressures_loop = []
for T in temps_C:
    log_P = A - B / (C + T)
    P = 10 ** log_P
    pressures_loop.append(P)
pressures_loop = np.array(pressures_loop)

print("Loop result:", pressures_loop)

# YOUR TASK: Write the vectorized version below
# pressures_vectorized = ???
Loop result: [   23.62071074    92.0401566    287.67697279   757.90576684
  1744.36521931  3601.23317886  6803.39300021 11943.43303501]

Exercise 1.2: Discussion - When Loops Are Okay#

Type: 💬 Discussion (5 min)

We learned that vectorization is faster than loops. But are there situations where loops are better or necessary?

With a partner, come up with 2-3 scenarios where you might still use a loop in scientific Python code.

Hint: Think about dependencies between iterations, readability, or operations that can’t be vectorized.

Scenarios where loops might be appropriate:

Exercise 1.3: Reflection - Broadcasting Intuition#

Type: 🤔 Reflection (3 min)

Broadcasting is one of NumPy’s most powerful features, but it can also cause subtle bugs.

Look at this code and predict the output shape without running it:

import numpy as np

A = np.array([[1, 2, 3],
              [4, 5, 6]])  # Shape: (2, 3)

B = np.array([10, 20, 30])  # Shape: (3,)

C = np.array([[100],
              [200]])  # Shape: (2, 1)

# Predict shapes before running:
# A + B = shape ???
# A + C = shape ???
# A + B + C = shape ???

Your predictions:

  • A + B =

  • A + C =

  • A + B + C =