0
0
NumPydata~10 mins

Correlation with np.correlate() in NumPy - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to calculate the correlation of two arrays using numpy.

NumPy
import numpy as np

x = np.array([1, 2, 3])
y = np.array([0, 1, 0])
result = np.correlate(x, y, [1])
print(result)
Drag options to blanks, or click blank then click option'
A"full"
B"valid"
C"same"
D"none"
Attempts:
3 left
💡 Hint
Common Mistakes
Using an invalid mode string causes an error.
Using "valid" or "same" changes the output size.
2fill in blank
medium

Complete the code to compute the correlation of two arrays with mode 'valid'.

NumPy
import numpy as np

a = np.array([1, 2, 3, 4])
b = np.array([0, 1, 0])
correlation = np.correlate(a, b, mode=[1])
print(correlation)
Drag options to blanks, or click blank then click option'
A"same"
B"partial"
C"valid"
D"full"
Attempts:
3 left
💡 Hint
Common Mistakes
Using an unsupported mode string causes an error.
Confusing "valid" with "full" changes the output length.
3fill in blank
hard

Fix the error in the code to correctly compute correlation with np.correlate.

NumPy
import numpy as np

x = np.array([1, 2, 3])
y = np.array([0, 1, 0])
result = np.correlate(x, y, [1])
print(result)
Drag options to blanks, or click blank then click option'
A"valid"
Bfull
Cvalid
D"full"
Attempts:
3 left
💡 Hint
Common Mistakes
Passing mode without quotes causes a TypeError.
Using an invalid mode string causes a ValueError.
4fill in blank
hard

Fill both blanks to create a dictionary comprehension that maps each number to its correlation with a fixed array.

NumPy
import numpy as np

fixed = np.array([1, 0, -1])
numbers = [1, 2, 3]
correlations = {num: np.correlate(np.array([num, num, num]), fixed, mode=[1])[[2]] for num in numbers}
print(correlations)
Drag options to blanks, or click blank then click option'
A"valid"
B"full"
C0
D-1
Attempts:
3 left
💡 Hint
Common Mistakes
Using an invalid mode string.
Using an index out of range.
5fill in blank
hard

Fill all three blanks to create a dictionary comprehension that maps each word to the correlation of its length with a fixed array.

NumPy
import numpy as np

fixed = np.array([1, 2, 3])
words = ["cat", "dog", "bird"]
correlation_dict = {word: np.correlate(np.array([len(word)] * 3), fixed, mode=[1])[[2]] for word in words if len(word) [3] 3}
print(correlation_dict)
Drag options to blanks, or click blank then click option'
A"valid"
B0
C>
D"full"
Attempts:
3 left
💡 Hint
Common Mistakes
Using incorrect mode strings.
Using wrong index values.
Using wrong comparison operators.