我有两个numpy数组a
和b
。我有一个定义,它构造了一个数组c
,其元素是数组中不同元素的所有可能和
import numpy as np
def Sumarray(a):
n = len(a)
sumarray = np.array([0]) # Add a default zero element
for k in range(2,n+1):
full = np.mgrid[k*(slice(n),)]
nd_triu_idx = full[:,(np.diff(full,axis=0)>0).all(axis=0)]
sumarray = np.append(sumarray, a[nd_triu_idx].sum(axis=0))
return sumarray
a = np.array([1,2,6,8])
c = Sumarray(a)
print(d)
然后,我在c
和b
的元素之间执行一个子集:isSubsetSum
返回b
的元素,求和后得到c[1]。假设我
c[0] = b[2] + b[3]
然后我想删除:
a
的元素,求和后得到c[0]从定义Sumarray
可以看出,a
的不同元素的和的顺序被保留,因此我需要实现一些映射。你知道吗
函数isSubsetSum
由
def _isSubsetSum(numbers, n, x, indices):
if (x == 0):
return True
if (n == 0 and x != 0):
return False
# If last element is greater than x, then ignore it
if (numbers[n - 1] > x):
return _isSubsetSum(numbers, n - 1, x, indices)
# else, check if x can be obtained by any of the following
found = _isSubsetSum(numbers, n - 1, x, indices)
if found: return True
indices.insert(0, n - 1)
found = _isSubsetSum(numbers, n - 1, x - numbers[n - 1], indices)
if not found: indices.pop(0)
return found
def isSubsetSum(numbers, x):
indices = []
found = _isSubsetSum(numbers, len(numbers), x, indices)
return indices if found else None
当您迭代所有可能的项数时,您也可以直接生成all可能的子集。你知道吗
这些可以方便地编码为数字0,1,2,。。。通过它们的二进制表示法:O表示完全没有项,1表示只有第一项,2表示只有第二项,3表示第一项和第二项,依此类推。你知道吗
使用此方案,从和索引中恢复项变得非常容易,因为我们只需获得二进制表示:
更新:我们可以用少量的额外代码来抑制1项和:
运行示例:
相关问题 更多 >
编程相关推荐