更快的numpy-solution而不是itertools.combinations?

更快的numpy-solution而不是itertools.combinations?,第1张

更快的numpy-solution而不是itertools.combinations?

这是一个比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


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5667094.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存