As a challenge, I've given myself this problem:
Given 2 lists, A, and B, where B is a shuffled version of A, the idea is to figure out the shuffled indices.
For example:
A = [10, 40, 30, 2]
B = [30, 2, 10, 40]
result = [2, 3, 0, 1]
A[2] A[3] A[0] A[1]
|| || || ||
30 2 10 40
Note that ties for identical elements can be resolved arbitrarily.
I've come up with a solution that involves the use of a dictionary to store indices. What other possible solutions does this problem have? A solution using a library also works. Numpy, pandas, anything is fine.
We can make use of np.searchsorted
with its optional sorter
argument -
sidx = np.argsort(B)
out = sidx[np.searchsorted(B,A, sorter=sidx)]
Sample run -
In [19]: A = [10, 40, 30, 2, 40]
...: B = [30, 2, 10, 40]
...:
In [20]: sidx = np.argsort(B)
In [21]: sidx[np.searchsorted(B,A, sorter=sidx)]
Out[21]: array([2, 3, 0, 1, 3])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With