Challenge - 5 Problems
dtype Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate1:30remaining
Output of numpy array with specified dtype
What is the output of this code snippet?
import numpy as np arr = np.array([1, 2, 3], dtype='float32') print(arr.dtype)
NumPy
import numpy as np arr = np.array([1, 2, 3], dtype='float32') print(arr.dtype)
Attempts:
2 left
💡 Hint
Check the dtype argument passed during array creation.
✗ Incorrect
The dtype argument 'float32' forces the array elements to be 32-bit floating point numbers, so arr.dtype is float32.
❓ data_output
intermediate2:00remaining
Resulting array values with dtype conversion
What is the output array when specifying dtype as int8 for this input?
import numpy as np arr = np.array([300, -130, 127], dtype='int8') print(arr)
NumPy
import numpy as np arr = np.array([300, -130, 127], dtype='int8') print(arr)
Attempts:
2 left
💡 Hint
Remember int8 stores values from -128 to 127 and wraps around on overflow.
✗ Incorrect
int8 values wrap around using modulo 256 arithmetic. 300 % 256 = 44, -130 % 256 = 126, 127 unchanged. Thus, the array is [44 126 127].
🔧 Debug
advanced1:30remaining
Identify error when specifying dtype incorrectly
What error does this code raise?
import numpy as np arr = np.array([1, 2, 3], dtype='flot64')
NumPy
import numpy as np arr = np.array([1, 2, 3], dtype='flot64')
Attempts:
2 left
💡 Hint
Check if the dtype string is a valid numpy type.
✗ Incorrect
The dtype string 'flot64' is misspelled and not recognized by numpy, causing a TypeError.
🚀 Application
advanced2:00remaining
Choosing dtype for memory optimization
You have a large dataset of integers ranging from 0 to 1000. Which dtype should you specify to minimize memory usage without losing data?
Attempts:
2 left
💡 Hint
Consider the range of values and the size limits of each dtype.
✗ Incorrect
np.uint16 can store integers from 0 to 65535 using 2 bytes, which covers 0 to 1000 efficiently. np.int8 and np.int32 either have too small or unnecessarily large ranges. np.float64 uses more memory and is for floats.
🧠 Conceptual
expert2:30remaining
Effect of dtype on arithmetic operations
Given two numpy arrays:
What is the output and dtype of result?
import numpy as np arr1 = np.array([1000], dtype='int16') arr2 = np.array([1000], dtype='int16') result = arr1 + arr2 print(result, result.dtype)
What is the output and dtype of result?
NumPy
import numpy as np arr1 = np.array([1000], dtype='int16') arr2 = np.array([1000], dtype='int16') result = arr1 + arr2 print(result, result.dtype)
Attempts:
2 left
💡 Hint
int16 max value is 32767; check if addition overflows.
✗ Incorrect
1000 + 1000 = 2000 fits within int16 range (-32768 to 32767). NumPy preserves the input dtype for arithmetic on same-type integer arrays, so result is [2000] int16. No upcasting or overflow.