Challenge - 5 Problems
Structured Arrays Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of a structured array creation
What is the output of this code that creates a structured array with fields 'name' and 'age'?
NumPy
import numpy as np person = np.array([('Alice', 25), ('Bob', 30)], dtype=[('name', 'U10'), ('age', 'i4')]) print(person)
Attempts:
2 left
💡 Hint
Look at the dtype and how the values are stored as integers or strings.
✗ Incorrect
The structured array stores 'name' as a Unicode string of max length 10 and 'age' as a 4-byte integer. The output shows the array with tuples of (name, age).
❓ data_output
intermediate1:30remaining
Number of elements in a structured array
How many elements are in this structured array?
NumPy
import numpy as np arr = np.array([(1, 2.5), (3, 4.5), (5, 6.5)], dtype=[('x', 'i4'), ('y', 'f4')]) print(len(arr))
Attempts:
2 left
💡 Hint
Count the number of tuples in the array creation.
✗ Incorrect
The array has three tuples, so its length is 3.
🔧 Debug
advanced2:00remaining
Identify the error in structured array creation
What error does this code raise when trying to create a structured array?
NumPy
import numpy as np arr = np.array([(1, 2.5), (3, '4.5')], dtype=[('x', 'i4'), ('y', 'f4')])
Attempts:
2 left
💡 Hint
Check the data types and the values provided for each field.
✗ Incorrect
The second tuple has '4.5' as a string, but the dtype expects a float. This causes a ValueError during conversion.
🚀 Application
advanced1:30remaining
Accessing fields in a structured array
Given this structured array, what is the output of printing arr['age']?
NumPy
import numpy as np arr = np.array([('John', 28), ('Jane', 32)], dtype=[('name', 'U10'), ('age', 'i4')]) print(arr['age'])
Attempts:
2 left
💡 Hint
Accessing a field returns an array of that field's values.
✗ Incorrect
arr['age'] returns a numpy array of the ages as integers, shown as [28 32].
🧠 Conceptual
expert2:30remaining
Memory layout of structured arrays
Which statement about the memory layout of numpy structured arrays is TRUE?
Attempts:
2 left
💡 Hint
Think about how numpy stores data for performance and memory efficiency.
✗ Incorrect
Numpy structured arrays store all fields in a single contiguous block of memory with fields laid out sequentially. This allows efficient memory use and access.