I'm solving a knapsack similar problem: which is to print out the first combination of objects that has value above a number but weight below a limit.
I have tried:
value = [10, 8, 7, 6, 4]
weight = [8, 4, 3, 3, 1]
name = ['A','B','C','D','E']
Wlimit = 8
Vlimit = 8
def ID(maxDepth):
for i in range(1, maxDepth):
knapsack = []
if (DFS(knapsack, 0, 0, i)):
return True
else:
print("cannot find solution")
return False
def DFS(knapsack, currentValue, currentWeight, maxDepth):
# If reached the maximum depth, stop recursing.
if maxDepth <= 0 : return False
if currentValue >= Vlimit and currentWeight <= Wlimit:
print(knapsack)
return True
for i in range(len(name)):
if name[i] not in knapsack:
if ((currentWeight + weight[i]) < Wlimit):
knapsack.append(name[i])
DFS(knapsack, currentValue + value[i], currentWeight + weight[i], maxDepth - 1)
knapsack = knapsack[:-1]
DFS(knapsack, currentValue, currentWeight, maxDepth - 1)
else:
DFS(knapsack, currentValue, currentWeight, maxDepth - 1)
return False
I know the tree looks like this
But I don't know how to fix the code with the correct logic Hope someone can give me a hand on it.
Thank you!!