Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy - group data into sum values

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: [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?

like image 537
atomh33ls Avatar asked Nov 01 '22 13:11

atomh33ls


1 Answers

Here's a naive implementation using 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.

like image 172
wflynny Avatar answered Nov 09 '22 14:11

wflynny