Challenge - 5 Problems
Structured dtype Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of structured dtype array creation
What is the output of this code snippet that creates a structured numpy array with fields 'name' and 'age'?
NumPy
import numpy as np dtype = [('name', 'U10'), ('age', 'i4')] data = np.array([('Alice', 25), ('Bob', 30)], dtype=dtype) print(data)
Attempts:
2 left
💡 Hint
Check the dtype definitions and how numpy stores integers and strings.
✗ Incorrect
The dtype specifies 'U10' for strings and 'i4' for 4-byte integers. The array stores names as strings and ages as integers, so the output shows tuples with string and integer values.
❓ data_output
intermediate1:30remaining
Number of fields in a structured dtype
Given this structured dtype, how many fields does it contain?
NumPy
import numpy as np dtype = [('id', 'i4'), ('score', 'f8'), ('passed', 'b1')] print(len(dtype))
Attempts:
2 left
💡 Hint
Count each tuple inside the dtype list.
✗ Incorrect
The dtype list has three tuples, each defining one field: 'id', 'score', and 'passed'. So the length is 3.
🔧 Debug
advanced2:00remaining
Identify the error in structured dtype definition
What error does this code raise when trying to create a structured dtype?
NumPy
import numpy as np dtype = [('name', 'U10'), ('age')] arr = np.array([('Alice', 25)], dtype=dtype)
Attempts:
2 left
💡 Hint
Check the dtype list elements format.
✗ Incorrect
Each field in dtype must be a tuple with field name and type. ('age') is a string, not a tuple, causing TypeError: data type not understood.
🚀 Application
advanced1:30remaining
Accessing fields in a structured array
Given this structured array, what is the output of accessing the 'score' field?
NumPy
import numpy as np dtype = [('name', 'U10'), ('score', 'f4')] data = np.array([('John', 88.5), ('Jane', 92.0)], dtype=dtype) print(data['score'])
Attempts:
2 left
💡 Hint
Accessing a field returns an array of that field's values.
✗ Incorrect
The 'score' field is float32, so accessing it returns a numpy array of floats: [88.5 92.0].
🧠 Conceptual
expert2:30remaining
Memory layout of structured dtypes
Which statement correctly describes the memory layout of a numpy structured array with fields of different types?
Attempts:
2 left
💡 Hint
Think about how numpy aligns data for performance.
✗ Incorrect
Numpy stores structured arrays with fields in order, adding padding if needed to align data types for efficient access.