python中的分数背包(无排序)

2024-05-29 10:37:20 发布

您现在位置:Python中文网/ 问答频道 /正文

作为在线课程的一部分,我正在尝试解决分数背包问题(贪婪算法)。我正在尝试在不排序的情况下对其进行编码。我知道这效率较低,但我想练习编写讲座中列出的算法,因为我是编程新手

无论如何,我设法用给定的示例输入对其进行编码并获得所需的结果,但由于某种原因,当我将其提交给Coursera时,我遇到了一个错误。有人能帮我解决这个问题吗?这是我的密码:

def get_optimal_value(capacity, weights, values):
    total_value = 0
    amounts = [0]*len(values)  
    value_density = [v/w for v,w in zip(values, weights)] # value density = values/weights

    while capacity > 0:

        # Update current maximum value density and its index
        current_max = max(value_density)
        current_index = value_density.index(current_max)    

        # Update amounts array for current iteration
        amounts[current_index] = min(weights[current_index], capacity)
        
        # Update values for next iteration
        total_value += amounts[current_index] * value_density[current_index]
        capacity -= amounts[current_index]
        weights[current_index] -= amounts[current_index]
        
        # Once a current item is fully put into the knapsack, remove it from consideration by setting the value density to 0
        # 0 value_density ensures that it will not be the 'current_max' in the next iteration
        if weights[current_index] == 0:
            value_density[current_index] = 0.001
    print(value_density)
    return total_value


if __name__ == "__main__":
    #data = list(map(int, input().split()))
    data = [3, 50, 60, 20, 100, 50, 120, 30]
    n, capacity = data[0:2]
    values = data[2:(2 * n + 2):2]
    weights = data[3:(2 * n + 2):2]
    opt_value = get_optimal_value(capacity, weights, values)
    print("{:.10f}".format(opt_value))

下面是Coursera上的错误(我使用了错误消息中提到的准确输入,并在IDE中得到了正确答案):

Failed case #1/13: (Wrong answer)
wrong output format: list index out of range
Input:
3 50
60 20
100 50
120 30

Your output:

Your stderr:
Traceback (most recent call last):
  File "fractional_knapsack.py", line 35, in <module>
    opt_value = get_optimal_value(capacity, weights, values)
  File "fractional_knapsack.py", line 12, in get_optimal_value
    current_max = max(value_density)
ValueError: max() arg is an empty sequence

Correct output:
180.000
 (Time used: 0.00/5.00, memory used: 9183232/671088640.)

Tags: theindatagetindexvalue错误optimal

热门问题