0
0
NumPydata~10 mins

np.setdiff1d() for difference 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 find elements in array1 that are not in array2 using np.setdiff1d().

NumPy
import numpy as np
array1 = np.array([1, 2, 3, 4, 5])
array2 = np.array([3, 4, 6])
difference = np.[1](array1, array2)
print(difference)
Drag options to blanks, or click blank then click option'
Aunique
Bunion1d
Cintersect1d
Dsetdiff1d
Attempts:
3 left
💡 Hint
Common Mistakes
Using np.union1d() which returns all unique elements from both arrays.
Using np.intersect1d() which returns common elements.
Using np.unique() which just returns unique elements of one array.
2fill in blank
medium

Complete the code to find the difference between two arrays and store it in 'diff'.

NumPy
import numpy as np
arr1 = np.array([10, 20, 30, 40])
arr2 = np.array([20, 50])
diff = np.[1](arr1, arr2)
print(diff)
Drag options to blanks, or click blank then click option'
Aintersect1d
Bsetdiff1d
Cunion1d
Dsort
Attempts:
3 left
💡 Hint
Common Mistakes
Using np.intersect1d() which returns common elements.
Using np.union1d() which returns all unique elements combined.
3fill in blank
hard

Fix the error in the code to correctly find the difference between arrays using np.setdiff1d().

NumPy
import numpy as np
x = np.array([5, 6, 7, 8])
y = np.array([7, 9])
diff = np.setdiff1d(x, [1])
print(diff)
Drag options to blanks, or click blank then click option'
Anp.array([7, 9])
B[7, 9]
Cy
Dx
Attempts:
3 left
💡 Hint
Common Mistakes
Passing the first array again as the second argument.
Passing a list literal instead of the array variable.
4fill in blank
hard

Fill both blanks to create a dictionary with words as keys and their lengths as values, but only for words longer than 3 characters.

NumPy
words = ['apple', 'bat', 'carrot', 'dog']
lengths = {word: [1] for word in words if [2]
print(lengths)
Drag options to blanks, or click blank then click option'
Alen(word)
Bword
Clen(word) > 3
Dword > 3
Attempts:
3 left
💡 Hint
Common Mistakes
Using the word itself as the value instead of its length.
Using the word variable in the condition instead of its length.
5fill in blank
hard

Fill all three blanks to create a dictionary of words and their lengths, but only include words with length greater than 3.

NumPy
words = ['sun', 'moon', 'star', 'sky']
lengths = { [1]: [2] for w in words if len(w) [3] 3}
print(lengths)
Drag options to blanks, or click blank then click option'
Aw.upper()
Blen(w)
C>
Dw
Attempts:
3 left
💡 Hint
Common Mistakes
Using uppercase words as keys instead of original words.
Using the word variable as value instead of length.
Using wrong comparison operators.