0
0
NumPydata~20 mins

Defining structured dtypes in NumPy - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Structured dtype Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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)
A[('Alice', 25) ('Bob', '30')]
B[('Alice', 25) ('Bob', 30)]
C[('Alice', '25') ('Bob', '30')]
D[('Alice', 25.0) ('Bob', 30.0)]
Attempts:
2 left
💡 Hint
Check the dtype definitions and how numpy stores integers and strings.
data_output
intermediate
1: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))
A4
B2
C1
D3
Attempts:
2 left
💡 Hint
Count each tuple inside the dtype list.
🔧 Debug
advanced
2: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)
AValueError: field definition must be a tuple
BNo error, array created successfully
CTypeError: data type not understood
DSyntaxError: invalid syntax
Attempts:
2 left
💡 Hint
Check the dtype list elements format.
🚀 Application
advanced
1: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'])
A[88.5 92. ]
B['88.5' '92.0']
C[('John', 88.5) ('Jane', 92.0)]
D[88 92]
Attempts:
2 left
💡 Hint
Accessing a field returns an array of that field's values.
🧠 Conceptual
expert
2:30remaining
Memory layout of structured dtypes
Which statement correctly describes the memory layout of a numpy structured array with fields of different types?
AFields are stored contiguously in memory in the order defined, with padding added to align data types.
BFields are stored randomly in memory without any order or alignment.
CAll fields are stored as separate arrays internally, not contiguous.
DFields are stored as strings regardless of their defined type.
Attempts:
2 left
💡 Hint
Think about how numpy aligns data for performance.