11 Set Routines Solutions
title: "Set routines" date: 2026-05-24T13:51:07Z
Set routines
1import numpy as np
1np.__version__
'1.11.2'
1author = 'kyubyong. longinglove@nate.com'
Making proper sets
Q1. Get unique elements and reconstruction indices from x. And reconstruct x.
1x = np.array([1, 2, 6, 4, 2, 3, 2])
2out, indices = np.unique(x, return_inverse=True)
3print "unique elements =", out
4print "reconstruction indices =", indices
5print "reconstructed =", out[indices]
unique elements = [1 2 3 4 6]
reconstruction indices = [0 1 4 3 1 2 1]
reconstructed = [1 2 6 4 2 3 2]
Boolean operations
Q2. Create a boolean array of the same shape as x. If each element of x is present in y, the result will be True, otherwise False.
1x = np.array([0, 1, 2, 5, 0])
2y = np.array([0, 1])
3print np.in1d(x, y)
[ True True False False True]
Q3. Find the unique intersection of x and y.
1x = np.array([0, 1, 2, 5, 0])
2y = np.array([0, 1, 4])
3print np.intersect1d(x, y)
[0 1]
Q4. Find the unique elements of x that are not present in y.
1x = np.array([0, 1, 2, 5, 0])
2y = np.array([0, 1, 4])
3print np.setdiff1d(x, y)
[2 5]
Q5. Find the xor elements of x and y.
1x = np.array([0, 1, 2, 5, 0])
2y = np.array([0, 1, 4])
3out1 = np.setxor1d(x, y)
4out2 = np.sort(np.concatenate((np.setdiff1d(x, y), np.setdiff1d(y, x))))
5assert np.allclose(out1, out2)
6print out1
[2 4 5]
Q6. Find the union of x and y.
1x = np.array([0, 1, 2, 5, 0])
2y = np.array([0, 1, 4])
3out1 = np.union1d(x, y)
4out2 = np.sort(np.unique(np.concatenate((x, y))))
5assert np.allclose(out1, out2)
6print np.union1d(x, y)
[0 1 2 4 5]