Python Fractional Knapsack - “列表索引超出范围”

时间:2016-11-07 02:58:59

标签: python knapsack-problem

# Uses python3
import sys

def get_optimal_value(capacity, weights, values):

    unit_value = [a/b for a,b in zip(values,weights)]
    m = len(unit_value)
    index = sorted(range(m), key = unit_value.__getitem__) # from biggest to smallest

    values = [values[i] for i in index]
    weights = [weights[i] for i in index]
#   unit_value = [unit_value[i] for i in index]
    unit_value = sorted(unit_value, key=int, reverse=True)

    if capacity == 0: return None
    for i in range(0,m):
        if sum(values) < capacity: return sum(values)
        if weights[index[i]] > capacity: return unit_value[i]*capacity
        if weights[index[i]] <= capacity: return values[index[i]] + get_optimal_value(capacity-weights[index[i]], weights, values)

if __name__ == "__main__":
    data = [int(x) for x in input("").split()]
    #data = list(map(int, sys.stdin.read().split()))
    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))

我想逐行提供以下输入:

3 50
60 20
100 50
120 30

然而,它在使用时显示错误答案120 "unit_value = [unit_value[i] for i in index]"。使用"unit_value = sorted(unit_value, key=int, reverse=True)"时,正确的答案是180。这两条线有什么区别?此外,当您引用列表的"list index out of range"元素时,它会导致问题n-th,而列表的长度小于n

0 个答案:

没有答案