0

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.

codinator
  • 1
  • 4
  • I don't know exactly what's wrong with your code, but code like `weights[efficiency.index(max(efficiency))]` makes my skin crawl. The simple solution is to create a list of tuples: `choices = [(values[i]/weights[i], values[i], weights[i]) for i in range(len(values))]`. Sort the list in descending order. Then go through the list adding items to the bag until either the bag fills up, or you run out of items. – user3386109 Apr 30 '23 at 00:07
  • I see that the code pops items out of the middle of the `efficiency` list, but I don't see that the code `pops` the corresponding item from the `weights` list. – user3386109 Apr 30 '23 at 00:25
  • 1
    Agreed, I dont think my solution is very elegant but I feel somewhat obliged to get it to work. You were right, popping the weights and values out of the list got the solution to work! Thanks – codinator Apr 30 '23 at 14:30

0 Answers0