I would like to find all the possible combinations of weighted elements in a set where the sum of their weights is exactly equal to a given weight W
Say I want to select k elements from the set { 'A', 'B', 'C', 'D', 'E' } where weights = {'A':2, 'B':1, 'C':3, 'D':2, 'E':1} and W = 4.
Then this would yield :
('A','B','E')
('A','D')
('B','C')
('B','D','E')
('C','E')
I realize the brute force way would be to find all permutations of the given set (with itertools.permutations) and splice out the first k elements with a weighted sum of W. But I’m dealing with at least 20 elements per set, which would be computationally expensive.
I think using a variant of knapsack would help, where only weight (not value) is considered and where the sum of weights must be equal to W (not inferior).
I want to implement this in python but any cs-theory hints would help. Bonus points for elegance!
Looping through all n! permutations is much too expensive. Instead, generate all 2^n subsets.
yields
This can be converted to sorted tuples by changing the return part of the list comprehension to
tuple(sorted(x)), or by replacing thelistcall inpowersetwith one tosorted.