【问题标题】:Efficient way to extend a numpy array with values that do not already exist in that array使用该数组中尚不存在的值扩展 numpy 数组的有效方法
【发布时间】:2016-09-03 11:17:19
【问题描述】:

我对 python/numpy 很陌生。我想将值存储在一个 numpy 数组中,这是一个简单组合问题的解决方案。 在这我有两个给定的值 x 和 y 以及一个带有 xx+by 满足 ax+by

问题是,我需要一个只出现一次的解决方案。就像在下面的代码示例中一样,对于 x=3、y=5 和 bound=20,解决方案 15 将是 (a,b)=(5,0) 的 a*3+b*5 的结果,也适用于(a,b)=(0,3)。我不需要冗余。到目前为止,我想出的最好方法是检查 if 块,如果计算的解决方案尚未存储,并且只有这样,该值才会添加到我的数组中。

除了在每个迭代步骤中检查整个现有数组之外,还有更有效的方法吗?就像除 np.append 之外的一个自动只存储值的函数一样,它还不存在? 或者有没有办法首先存储所有计算的解决方案,然后只返回一个具有非冗余值的数组? (这样会更有效率吗?)

PS:我正在处理非常大的界限,我的数组需要存储数千个值。

import numpy as np


x=3
y=5
bound=20


arr=([]) # empty array at first

for a in range(np.int(bound/x)+1):
    for b in range(np.int((bound-a*x)/y)+1):
        feasible_combination=a*x+b*y

        if feasible_combination not in arr[:]:  # no need for redundance 
            arr=np.append(arr,feasible_combination)
arr=np.sort(arr)
print(arr)

【问题讨论】:

  • 在列表中收集数组更快。或者对于唯一值,请考虑 set

标签: python-3.x numpy


【解决方案1】:

这里有两个更快的版本,一个使用set,另一个使用 NumPy 完成几乎所有的工作:

def combinations_set(x, y, bound):
    combs = set()
    for a in range(np.int(bound/x)+1):
        for b in range(np.int((bound-a*x)/y)+1):
            combs.add(a*x+b*y)
    return np.sort(list(combs))

def combinations_ix(x, y, bound):
    a, b = np.ix_(*[np.arange(int(bound/_)+1) for _ in (x, y)])
    combs = a*x + b*y
    return np.sort(np.unique(combs[combs <= bound]))

对于以下示例,与原始代码相比,combinations_ix 在我的机器上的速度提高了 1607 倍,但combinations_set 具有相当的竞争力(并且应该比combinations_ix 使用更少的内存):

In [58]: %timeit combinations(200, 234, 100000)   # original code as function
1 loops, best of 3: 8.23 s per loop

In [59]: %timeit combinations_set(200, 234, 100000)
100 loops, best of 3: 16.1 ms per loop

In [60]: %timeit combinations_ix(200, 234, 100000)
100 loops, best of 3: 5.12 ms per loop

【讨论】:

    猜你喜欢
    • 2011-12-09
    • 1970-01-01
    • 2012-02-21
    • 2020-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-15
    • 2011-10-28
    相关资源
    最近更新 更多