这是一个比itertools UPDATE快一点的:和(
nump2)实际上快得多的一个:
import numpy as npimport itertoolsimport timeitdef nump(n, k, i=0): if k == 1: a = np.arange(i, i+n) return tuple([a[None, j:] for j in range(n)]) template = nump(n-1, k-1, i+1) full = np.r_[np.repeat(np.arange(i, i+n-k+1), [t.shape[1] for t in template])[None, :], np.c_[template]] return tuple([full[:, j:] for j in np.r_[0, np.add.accumulate( [t.shape[1] for t in template[:-1]])]])def nump2(n, k): a = np.ones((k, n-k+1), dtype=int) a[0] = np.arange(n-k+1) for j in range(1, k): reps = (n-k+j) - a[j-1] a = np.repeat(a, reps, axis=1) ind = np.add.accumulate(reps) a[j, ind[:-1]] = 1-reps[1:] a[j, 0] = j a[j] = np.add.accumulate(a[j]) return adef itto(L, N): return np.array([a for a in itertools.combinations(L,N)]).Tk = 6n = 12N = np.arange(n)assert np.all(nump2(n,k) == itto(N,k))print('numpy ', timeit.timeit('f(a,b)', number=100, globals={'f':nump, 'a':n, 'b':k}))print('numpy 2 ', timeit.timeit('f(a,b)', number=100, globals={'f':nump2, 'a':n, 'b':k}))print('itertools', timeit.timeit('f(a,b)', number=100, globals={'f':itto, 'a':N, 'b':k}))
时间:
k = 3, n = 50numpy 0.06967267207801342numpy 2 0.035096961073577404itertools 0.7981023890897632k = 3, n = 10numpy 0.015058324905112386numpy 2 0.0017436158377677202itertools 0.004743851954117417k = 6, n = 12numpy 0.03546895203180611numpy 2 0.00997065706178546itertools 0.05292179994285107
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)