My code is:
def maxValueSelection(items,V):
maxval = 0
val = 0
sorted_dict={}
for i in items.items():
sorted_dict[i[1][1]] = [i[1][0],i[0]]
sorted_dict_list = (sorted(sorted_dict))[::-1]
while sorted_dict_list!=[]:
item = sorted_dict_list[0]
if(sorted_dict[item][0] + val<=V):
maxval+=item
val = val+sorted_dict[item][0]
sorted_dict_list.pop(0)
return maxval
items = {1:(4,400),2:(9,1800),3:(10,3500),4:(20,4000),5:(2,1000),6:(1,200)}
V = 20
print(maxValueSelection(items,V))
I have used a greedy algorithm for the question in which I have two values which records the value of the item and one monitors the weight of the items which should not be exceeded more than a threshold value mentioned in the question. It seems like my greedy strategy is working upto some extent but nearly misses the maxValue in every test case. It will be helpful if someone tells me how to fix this issue with my code