find combination of numbers that equal a given sum python

Solutions on MaxInterview for find combination of numbers that equal a given sum python by the best coders in the world

showing results for - "find combination of numbers that equal a given sum python"
Ainsley
04 Jan 2021
1def subsets_with_sum(lst, target, with_replacement=False):
2    x = 0 if with_replacement else 1
3    def _a(idx, l, r, t):
4        if t == sum(l): r.append(l)
5        elif t < sum(l): return
6        for u in range(idx, len(lst)):
7            _a(u + x, l + [lst[u]], r, t)
8        return r
9    return _a(0, [], [], target)
10
11vals = [1, 5, 3, 7, 9]
12target = 12
13subsets_with_sum(lst, K, with_replacement=False)
14>>> [[5, 7], [3, 9]]
15
16vals = [57, 71, 87, 97, 99, 101, 103, 113, 114, 115,
17        128, 129, 131, 137, 147, 156, 163, 186]
18target = 270
19subsets_with_sum(vals, target, with_replacement=False)
20>>> [[57, 99, 114], [114, 156]]
21