Review: Debugging Questions (NumPy)

Module 4: IDEs & Tools

Debugging Questions (NumPy)

import numpy as np
Exercise

The code aims to reshape a flat array into a 3D array. However, it results in an error. Identify and fix the error(s).

arr = np.arange(27)
arr_3d = arr.reshape((3, 3))  # Error
print("3D Array:\n", arr_3d)
ValueError: cannot reshape array of size 27 into shape (3,3)
Exercise

The code is supposed to compute the cumulative product of an array. However, it gives incorrect output. Identify and fix the error(s).

arr = np.array([[1, 2, 3, 4]])

cum_prod = np.cumsum(arr, axis=0)
print("Cumulative product:", cum_prod)
# Expected: [[1, 2, 6, 24]]
# Output: [[1 2 3 4]]
Cumulative product: [[1 2 3 4]]
Exercise

This code attempts to select elements from a NumPy array based on a condition. However, it raises an error ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all(). Identify and fix the error(s).

arr = np.arange(10)

# Select elements greater than 5 and less than 8
selected = arr[arr > 5 and arr < 8.0]  # Error
print("Selected elements:", selected)  # Expected: [6, 7]
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
Exercise

You wrote the following code to see how fixing a seed ensures the random generators always return the same number. However, every step of the for loop shows a different number. What is happening?

for _ in range(10):
  x = np.random.randint(low=0, high=1000)
  np.random.seed(x)
  print(x)
207
518
105
704
495
665
233
999
448
988