This problem has been asked before: the problem however I have been struggling for a while to debug where my logic is wrong because my algorithm fails on this unknown test case:
Failed case #7/13: Wrong answer
got: 101649.0055882329 expected: 66152.572
(Time used: 0.01/5.00, memory used: 11288576/2684354560.)
My code and logic:
def get_optimal_value(capacity, weights, values):
value = 0.
# Create a list of most efficient weight
efficiency = [values[i] / weights[i] for i in range(len(values))]
while capacity > 0:
# if capacity is greater than the amount of the most efficient weight
if capacity >= weights[efficiency.index(max(efficiency))]:
value = value + max(efficiency) * weights[efficiency.index(max(efficiency))]
capacity -= weights[efficiency.index(max(efficiency))]
# weight of most efficient object should be 0
weights[efficiency.index(max(efficiency))] -= weights[efficiency.index(max(efficiency))]
# if capacity is less than the amount of the most efficient weight
elif capacity <= weights[efficiency.index(max(efficiency))]:
value = value + max(efficiency) * capacity
return value
# if weight of most efficient object is 0, then remove from 'efficiency' list
if weights[efficiency.index(max(efficiency))] <= 0:
efficiency.pop(efficiency.index(max(efficiency)))
if len(efficiency) == 0:
return value
return value
Any suggestions as to why my logic is flawed would be greatly appreciated.