Say I have an array of values:
假设我有一系列值:
a = np.array([1,5,4,2,4,3,1,2,4])
and three 'sum' values:
和三个'和'值:
b = 10
c = 9
d = 7
Is there a way to group the values in a
into groups of sets where the values combine to equal b,c and d? For example:
有没有办法将值组合成一组集合,其中值组合起来等于b,c和d?例如:
b: [5,2,3]
c: [4,4,1]
d: [4,2,1]
b: [5,4,1]
c: [2,4,3]
d: [4,2,1]
b: [4,2,4]
c: [5,4]
d: [1,1,2,3]
Note the sum of b
,c
and d
should remain the same (==26). Perhaps this operation already has a name?
注意b,c和d的总和应保持不变(== 26)。也许这个操作已经有了名字?
1 个解决方案
#1
2
Here's a naive implementation using itertools
这是使用itertools的简单实现
from itertools import chain, combinations
def group(n, iterable):
s = list(iterable)
return [c for c in chain.from_iterable(combinations(s, r)
for r in range(len(s)+1))
if sum(c) == n]
group(5, range(5))
yields
[(1, 4), (2, 3), (0, 1, 4), (0, 2, 3)]
Note, this probably will be very slow for large lists because we're essentially constructing and filtering through the power set of that list.
注意,这对于大型列表来说可能会非常慢,因为我们实际上是在构建和过滤该列表的电源集。
You could use this for
你可以用这个
sum_vals = [10, 9, 7]
a = [1, 5, 4, 2, 4, 3, 1, 2, 4]
map(lambda x: group(x, a), sum_vals)
and then zip
them together.
然后将它们压缩在一起。
#1
2
Here's a naive implementation using itertools
这是使用itertools的简单实现
from itertools import chain, combinations
def group(n, iterable):
s = list(iterable)
return [c for c in chain.from_iterable(combinations(s, r)
for r in range(len(s)+1))
if sum(c) == n]
group(5, range(5))
yields
[(1, 4), (2, 3), (0, 1, 4), (0, 2, 3)]
Note, this probably will be very slow for large lists because we're essentially constructing and filtering through the power set of that list.
注意,这对于大型列表来说可能会非常慢,因为我们实际上是在构建和过滤该列表的电源集。
You could use this for
你可以用这个
sum_vals = [10, 9, 7]
a = [1, 5, 4, 2, 4, 3, 1, 2, 4]
map(lambda x: group(x, a), sum_vals)
and then zip
them together.
然后将它们压缩在一起。