, @Inspired, NumPy , , NumPy, NumPy C/Fortran, -by-item Python.
, O(n log n), , O(n) Python. np.unique :
import numpy as np
def nlargest_indices(arr, n):
uniques = np.unique(arr)
threshold = uniques[-n]
return np.where(arr >= threshold)
full = np.random.random((1002,1004))
x, y = nlargest_indices(full, 10)
print(full[x, y])
print(x)
print(y)
nlargest_indices ()
def nlargest_indices_orig(full, n):
full = full.copy()
x = np.zeros(n)
y = np.zeros(n)
for idx in range(n):
x[idx] = np.unravel_index(full.argmax(), full.shape)[0]
y[idx] = np.unravel_index(full.argmax(), full.shape)[1]
full[full == full.max()] = 0.
return x, y
In [97]: %timeit nlargest_indices_orig(full, 500)
1 loops, best of 3: 5 s per loop
In [98]: %timeit nlargest_indices(full, 500)
10 loops, best of 3: 133 ms per loop
timeit nlargest_indices_orig, full .
:
def base(full, n):
full = full.copy()
In [102]: %timeit base(full, 500)
100 loops, best of 3: 4.11 ms per loop
, 4 5s nlargest_indices_orig.
: nlargest_indices nlargest_indices_orig , arr .
nlargest_indices n arr, x y, .
nlargest_indices_orig n arr, x y . x y, , , , .
, , .