0
0
NumPydata~20 mins

Convolution with np.convolve() in NumPy - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Convolution Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of simple 1D convolution
What is the output of this code using np.convolve() with default mode?
NumPy
import numpy as np
x = np.array([1, 2, 3])
h = np.array([0, 1, 0.5])
result = np.convolve(x, h)
print(result)
A[0. 1. 2.5 4. 1.5]
B[1. 2. 3. 0. 0.5]
C[0. 1. 2. 3. 1.5]
D[0. 1. 2.5 3. 1.5]
Attempts:
2 left
💡 Hint
Remember that default mode is 'full' which gives the complete convolution result.
data_output
intermediate
1:30remaining
Length of convolution output with 'valid' mode
Given two arrays a = np.array([1, 2, 3, 4]) and b = np.array([1, 0, -1]), what is the length of the output when convolving with mode='valid'?
NumPy
import numpy as np
a = np.array([1, 2, 3, 4])
b = np.array([1, 0, -1])
result = np.convolve(a, b, mode='valid')
print(len(result))
A4
B2
C3
D6
Attempts:
2 left
💡 Hint
Length in 'valid' mode is max(len(a), len(b)) - min(len(a), len(b)) + 1.
🔧 Debug
advanced
2:00remaining
Identify the error in convolution code
What error does this code raise when run?
NumPy
import numpy as np
x = np.array([1, 2, 3])
h = np.array([[0, 1, 0.5]])
result = np.convolve(x, h)
print(result)
ATypeError: object of type 'numpy.ndarray' has no len()
BValueError: object too deep for desired array
CTypeError: cannot perform reduce with flexible type
DTypeError: 1D arrays expected
Attempts:
2 left
💡 Hint
Check the shape of the arrays passed to np.convolve.
🧠 Conceptual
advanced
1:30remaining
Effect of 'same' mode in np.convolve()
Which statement best describes the output length when using np.convolve(a, b, mode='same')?
AOutput length matches the length of the first input array.
BOutput length is the maximum of the two input lengths.
COutput length matches the length of the second input array.
DOutput length is always the sum of input lengths minus one.
Attempts:
2 left
💡 Hint
The 'same' mode centers the full convolution output to match the first input's length.
🚀 Application
expert
2:30remaining
Using convolution to compute moving average
You want to compute a simple moving average of window size 3 on array data = np.array([1, 2, 3, 4, 5]). Which np.convolve() call produces the correct moving average values aligned with the original data length?
Anp.convolve(data, np.ones(3)/3, mode='full')
Bnp.convolve(data, np.ones(3)/3, mode='valid')
Cnp.convolve(data, np.ones(3)/3, mode='same')
Dnp.convolve(data, np.ones(3), mode='same') / 3
Attempts:
2 left
💡 Hint
Moving average should have the same length as data and average over 3 points centered.