Generating a numpy array with all combinations of numbers that sum to less than a given number

后端 未结 2 2242
隐瞒了意图╮
隐瞒了意图╮ 2021-02-14 09:56

There are several elegant examples of using numpy in Python to generate arrays of all combinations. For example the answer here: Using numpy to build an array of all combination

2条回答
  •  太阳男子
    2021-02-14 10:31

    I don't know what's a numpy approach, but here's a reasonably clean solution. Let A be an array of integers and let k be a number that you are given as input.

    Start with an empty array B; keep the sum of the array B in a variable s (initially set to zero). Apply the following procedure:

    • if the sum s of the array B is less than k, then (i) add it to the collection, (ii) and for each element from the original array A, add that element to B and update s, (iii) delete it from A and (iv) recursively apply the procedure; (iv) when the call returns, add the element back to A and update s; else do nothing.

    This bottom-up approach prunes invalid branches early on and only visits the necessary subsets (i.e. almost only the subsets that sum to less than k).

提交回复
热议问题