0
0
NumPydata~20 mins

np.setdiff1d() for difference in NumPy - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Set Difference Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of np.setdiff1d() with simple arrays
What is the output of the following code snippet?
NumPy
import numpy as np

arr1 = np.array([1, 2, 3, 4, 5])
arr2 = np.array([3, 4, 6])
result = np.setdiff1d(arr1, arr2)
print(result)
A[1 2 3 4 5 6]
B[3 4 6]
C[1 2 5]
D[6]
Attempts:
2 left
💡 Hint
np.setdiff1d returns elements in the first array that are NOT in the second array.
data_output
intermediate
1:30remaining
Number of elements in difference array
How many elements are in the resulting array after running this code?
NumPy
import numpy as np

arr1 = np.array([10, 20, 30, 40, 50])
arr2 = np.array([20, 40, 60])
result = np.setdiff1d(arr1, arr2)
print(len(result))
A3
B2
C4
D5
Attempts:
2 left
💡 Hint
Count elements in arr1 that are not in arr2.
🔧 Debug
advanced
1:30remaining
Identify the error in using np.setdiff1d with lists
What error will this code produce?
NumPy
import numpy as np

list1 = [1, 2, 3]
list2 = [2, 3, 4]
result = np.setdiff1d(list1, list2)
print(result)
ASyntaxError
B[1]
CTypeError: unhashable type: 'list'
DNo error, output: [1]
Attempts:
2 left
💡 Hint
np.setdiff1d can accept lists as input because it converts them internally to arrays.
Predict Output
advanced
2:00remaining
Output of np.setdiff1d with repeated elements
What is the output of this code?
NumPy
import numpy as np

arr1 = np.array([1, 2, 2, 3, 4, 4, 5])
arr2 = np.array([2, 4])
result = np.setdiff1d(arr1, arr2)
print(result)
A[1 3 5]
B[1 2 3 4 5]
C[1 3 4 5]
D[2 4]
Attempts:
2 left
💡 Hint
np.setdiff1d returns unique sorted values from arr1 not in arr2.
🚀 Application
expert
2:30remaining
Using np.setdiff1d to find missing data entries
Given two arrays representing IDs of users who completed two different surveys, which option correctly finds users who completed the first survey but NOT the second?
NumPy
import numpy as np

survey1 = np.array([101, 102, 103, 104, 105])
survey2 = np.array([102, 104, 106])
missing_users = ???
print(missing_users)
Anp.union1d(survey1, survey2)
Bnp.setdiff1d(survey1, survey2)
Cnp.intersect1d(survey1, survey2)
Dnp.setdiff1d(survey2, survey1)
Attempts:
2 left
💡 Hint
We want users in survey1 but not in survey2.