这是一个修改这个问题 https://stackoverflow.com/questions/40410766/summing-all-possible-combinations-of-an-arbitrary-number-of-arrays-and-applying除了元素本身之外,我还想返回数组元素的索引。我已经修改成功了arraysums()
, arraysums_recursive()
,但我正在挣扎arraysums_recursive_anyvals()
。详细信息如下:
我修改了arraysums()
:
def arraysums(arrays,lower,upper):
products = itertools.product(*arrays)
result = list()
indices = itertools.product(*[np.arange(len(arr)) for arr in arrays])
index = list()
for n,k in zip(products,indices):
s = sum(n)
if lower <= s <= upper:
result.append(n)
index.append(k)
return result,index
现在它返回元素和元素的索引:
N = 8
a = np.arange(N)
b = np.arange(N)-N/2
arraysums((a,b),lower=5,upper=6)
([(2, 3),
(3, 2),
(3, 3),
(4, 1),
(4, 2),
(5, 0),
(5, 1),
(6, -1),
(6, 0),
(7, -2),
(7, -1)],
[(2, 7),
(3, 6),
(3, 7),
(4, 5),
(4, 6),
(5, 4),
(5, 5),
(6, 3),
(6, 4),
(7, 2),
(7, 3)])
我还修改了 @unutbu 的递归解决方案,它也返回与arraysums()
:
def arraysums_recursive(arrays, lower, upper):
if len(arrays) <= 1:
result = [(item,) for item in arrays[0] if lower <= item <= upper]
index = [] # this needs to be fixed
else:
result = []
index = []
for item in arrays[0]:
subarrays = [[item2 for item2 in arr if item2 <= upper-item]
for arr in arrays[1:]]
result.extend(
[(item,)+tup for tup in arraysums(
subarrays, lower-item, upper-item)[0]])
index.extend(
[(item,)+tup for tup in arraysums(
subarrays, lower-item, upper-item)[1]])
return result,index
最后我修改了arraysums_recursive_anyvals()
,但我似乎无法理解为什么它不返回索引:
def arraysums_recursive_anyvals(arrays, lower, upper):
if len(arrays) <= 1:
result = [(item,) for item in arrays[0] if lower <= item <= upper]
index = [] # this needs to be fixed
else:
minval = min(item for arr in arrays for item in arr)
# Subtract minval from arrays to guarantee all the values are positive
arrays = [[item-minval for item in arr] for arr in arrays]
# Adjust the lower and upper bounds accordingly
lower -= minval*len(arrays)
upper -= minval*len(arrays)
result = []
index = []
for item in arrays[0]:
subarrays = [[item2 for item2 in arr if item2 <= upper-item]
for arr in arrays[1:]]
if min(len(arr) for arr in subarrays) == 0:
continue
result.extend(
[(item,)+tup for tup in arraysums_recursive(
subarrays, lower-item, upper-item)[0]])
index.extend(
[(item,)+tup for tup in arraysums_recursive(
subarrays, lower-item, upper-item)[1]])
# Readjust the result by adding back minval
result = [tuple([item+minval for item in tup]) for tup in result]
return result,index
results:
arraysums_recursive_anyvals((a,b),lower=5,upper=6)
([(2, 3),
(3, 2),
(3, 3),
(4, 1),
(4, 2),
(5, 0),
(5, 1),
(6, -1),
(6, 0),
(7, -2),
(7, -1)],
[])