Answers for "find combination of numbers that equal a given sum python"

0

find combination of numbers that equal a given sum python

def subsets_with_sum(lst, target, with_replacement=False):
    x = 0 if with_replacement else 1
    def _a(idx, l, r, t):
        if t == sum(l): r.append(l)
        elif t < sum(l): return
        for u in range(idx, len(lst)):
            _a(u + x, l + [lst[u]], r, t)
        return r
    return _a(0, [], [], target)

vals = [1, 5, 3, 7, 9]
target = 12
subsets_with_sum(lst, K, with_replacement=False)
>>> [[5, 7], [3, 9]]

vals = [57, 71, 87, 97, 99, 101, 103, 113, 114, 115,
        128, 129, 131, 137, 147, 156, 163, 186]
target = 270
subsets_with_sum(vals, target, with_replacement=False)
>>> [[57, 99, 114], [114, 156]]
Posted by: Guest on August-03-2021

Code answers related to "find combination of numbers that equal a given sum python"

Python Answers by Framework

Browse Popular Code Answers by Language