Incorrect order like 'import correlate from scipy.signal'
3. What is the output of this code?
import numpy as np
from scipy.signal import correlate
x = np.array([1, 2, 3])
y = np.array([0, 1, 0.5])
result = correlate(x, y, mode='full')
print(result)
medium
A. [0.5 2. 3.5 3. 0. ]
B. [0. 1. 2.5 3. 1.5]
C. [0. 1. 2. 3. 4.]
D. [1. 2. 3. 0. 0.5]
Solution
Step 1: Understand correlation calculation
Correlation slides the reversed y over x and sums element-wise products at each shift. Equivalent to np.convolve(x, np.flip(y), mode='full').
You want to find the shift where sensor2 best matches sensor1 using correlation. Which code snippet correctly finds the shift index with the highest correlation?
hard
A. import numpy as np
from scipy.signal import correlate
corr = correlate(sensor1, sensor2, mode='full')
shift = np.argmax(corr) - (len(sensor2) - 1)
print(shift)
B. import numpy as np
from scipy.signal import correlate
corr = correlate(sensor2, sensor1, mode='valid')
shift = np.argmax(corr)
print(shift)
C. import numpy as np
from scipy.signal import correlate
corr = correlate(sensor1, sensor2, mode='same')
shift = np.argmax(corr)
print(shift)
D. import numpy as np
from scipy.signal import correlate
corr = correlate(sensor1, sensor2)
shift = np.argmin(corr)
print(shift)
Solution
Step 1: Use 'full' mode for complete correlation
To find best matching shift, full correlation output is needed to cover all shifts.
Step 2: Calculate shift index correctly
Shift index = position of max correlation minus (length of second array - 1) to center shifts around zero.
Step 3: Verify code correctness
import numpy as np
from scipy.signal import correlate
corr = correlate(sensor1, sensor2, mode='full')
shift = np.argmax(corr) - (len(sensor2) - 1)
print(shift) uses full mode, np.argmax, and correct shift calculation.
Final Answer:
import numpy as np
from scipy.signal import correlate
corr = correlate(sensor1, sensor2, mode='full')
shift = np.argmax(corr) - (len(sensor2) - 1)
print(shift) -> Option A
Quick Check:
Full mode + argmax - (len(y)-1) = correct shift [OK]
Hint: Use full mode and adjust argmax by (len(y)-1) for shift [OK]
Common Mistakes:
Using 'valid' or 'same' mode which limits shifts
Using argmin instead of argmax
Not adjusting shift index by array length
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.