0
0
NumPydata~10 mins

np.einsum() for efficient computation 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 compute the sum of elements in array using np.einsum.

NumPy
import numpy as np
arr = np.array([1, 2, 3, 4])
sum_val = np.einsum('[1]', arr)
print(sum_val)
Drag options to blanks, or click blank then click option'
A'i->'
B'i->i'
C'ij->i'
D'i,i->'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'i,i->' which expects two arrays.
Using 'ij->i' which is for 2D arrays.
Using 'i->i' which returns the array unchanged.
2fill in blank
medium

Complete the code to compute the dot product of two vectors using np.einsum.

NumPy
import numpy as np
v1 = np.array([1, 2, 3])
v2 = np.array([4, 5, 6])
dot_product = np.einsum('[1]', v1, v2)
print(dot_product)
Drag options to blanks, or click blank then click option'
A'ij,jk->ik'
B'i,j->ij'
C'i,i->'
D'i->'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'i->' which sums only one vector.
Using 'ij,jk->ik' which is for matrix multiplication.
Using 'i,j->ij' which computes outer product.
3fill in blank
hard

Fix the error in the code to perform matrix multiplication using np.einsum.

NumPy
import numpy as np
A = np.array([[1, 2], [3, 4]])
B = np.array([[5, 6], [7, 8]])
result = np.einsum('[1]', A, B)
print(result)
Drag options to blanks, or click blank then click option'
A'ij,jk->ik'
B'ij,ik->jk'
C'ji,kj->ik'
D'ij,jk->ij'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'ij,ik->jk' which mismatches indices.
Using 'ji,kj->ik' which reverses indices incorrectly.
Using 'ij,jk->ij' which does not reduce the summed index.
4fill in blank
hard

Fill both blanks to create a dictionary comprehension that maps words to their lengths only if length is greater than 3.

NumPy
words = ['apple', 'bat', 'carrot', 'dog']
lengths = {word: [1] for word in words if [2]
Drag options to blanks, or click blank then click option'
Alen(word)
Blen(word) > 3
Cword
Dlen(words)
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'word' as value instead of length.
Using 'len(words)' which is the total number of words.
Using condition without comparison operator.
5fill in blank
hard

Fill all three blanks to create a dictionary comprehension that maps uppercase words to their lengths only if length is greater than 3.

NumPy
words = ['apple', 'bat', 'carrot', 'dog']
lengths = [1]: [2] for word in words if [3]
Drag options to blanks, or click blank then click option'
Aword.upper()
Blen(word)
Clen(word) > 3
Dword.lower()
Attempts:
3 left
💡 Hint
Common Mistakes
Using word.lower() instead of upper().
Using word as key without conversion.
Missing the length condition or using wrong comparison.