0
0
NumPydata~20 mins

np.union1d() for union in NumPy - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Union Mastery with np.union1d()
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of np.union1d() with integer arrays
What is the output of this code snippet using np.union1d()?
NumPy
import numpy as np
arr1 = np.array([1, 3, 5, 7])
arr2 = np.array([3, 4, 5, 6])
result = np.union1d(arr1, arr2)
print(result)
A[1 3 4 5 6 7]
B[1 3 5 7 3 4 5 6]
C[3 4 5 6]
D[1 3 5 7]
Attempts:
2 left
💡 Hint
np.union1d() returns sorted unique elements from both arrays combined.
data_output
intermediate
1:30remaining
Number of elements in union of two arrays
Given two arrays, how many elements are in the union computed by np.union1d()?
NumPy
import numpy as np
arr1 = np.array([10, 20, 30, 40])
arr2 = np.array([30, 40, 50, 60, 70])
union = np.union1d(arr1, arr2)
print(len(union))
A8
B5
C7
D6
Attempts:
2 left
💡 Hint
Count unique elements after merging both arrays.
🔧 Debug
advanced
1:30remaining
Identify the error in using np.union1d() with lists
What error will this code raise?
NumPy
import numpy as np
list1 = [1, 2, 3]
list2 = [3, 4, 5]
result = np.union1d(list1, list2)
print(result)
ANo error, prints [1 2 3 4 5]
BTypeError: unhashable type: 'list'
CValueError: operands could not be broadcast together
D[1 2 3 4 5]
Attempts:
2 left
💡 Hint
np.union1d() accepts array-like inputs, including lists.
🧠 Conceptual
advanced
2:00remaining
Behavior of np.union1d() with string arrays
What is the output of this code?
NumPy
import numpy as np
arr1 = np.array(['apple', 'banana', 'cherry'])
arr2 = np.array(['banana', 'date', 'fig'])
result = np.union1d(arr1, arr2)
print(result)
A['apple' 'banana' 'banana' 'cherry' 'date' 'fig']
B['apple' 'banana' 'cherry' 'date' 'fig']
C['banana' 'date' 'fig']
D['apple' 'cherry' 'date' 'fig']
Attempts:
2 left
💡 Hint
np.union1d() works with strings and sorts them alphabetically.
🚀 Application
expert
2:30remaining
Using np.union1d() to find unique categories from two datasets
You have two datasets with category labels as arrays. Which code snippet correctly finds all unique categories combined?
Aunique_categories = np.setdiff1d(dataset1['category'], dataset2['category'])
Bunique_categories = np.concatenate((dataset1['category'], dataset2['category']))
Cunique_categories = np.intersect1d(dataset1['category'], dataset2['category'])
Dunique_categories = np.union1d(dataset1['category'], dataset2['category'])
Attempts:
2 left
💡 Hint
np.union1d() returns all unique elements from both arrays combined.