I found this very handy example code which implements a DP solution to the knapsack problem (kudos to the person who posted it).
I am trying to modify it to include a constraint on the number of items k in the knapsack.
I added a third argument
def knapsack(items, maxweight, maxitems):
and modified the reconstruction as follows:
while i > 0:
if bestvalues[i][j] != bestvalues[i - 1][j] and len(reconstruction) < maxitems:
reconstruction.append(items[i - 1])
j -= items[i - 1][1]
i -= 1
Provided I input enough items to choose from this will always converge to the desired k number of items. However, I am fairly certain that this is not finding the closest approximation of the global optimum. The discussions I have read after some searching refer to adding a third dimension k and accounting for the constraint before the reconstruction (I *think this would be during the best value assessment).
Can someone provide an example of how to do this? Ideally a working python example would be fantastic but I'll settle for pseudocode. I have read a few instructions using notation but I am still not sure how to constrain with k (outside of what I have done here).
Thanks!