从多维背包算法获得有关最优解的信息

时间:2018-07-20 18:19:09

标签: python algorithm pandas optimization knapsack-problem

我正在构建多维背包算法,以优化幻想NASCAR阵容。我要感谢另一位作者的代码,现在正尝试将最佳解决方案所包含的驱动程序拼凑起来。我已经在标准情况下编写了代码来执行此操作,但是正在努力通过增加尺寸来解决它。这是我的代码:

#open csv file
df = pd.read_csv('roster_kentucky_july18.csv')

print(df.head())

def knapsack2(n, weight, count, values, weights):
    dp = [[[0] * (weight + 1) for _ in range(n + 1)] for _ in range(count + 1)]
    for z in range(1, count + 1):
        for y in range(1, n + 1):
            for x in range(weight + 1):
                if weights[y - 1] <= x:
                    dp[z][y][x] = max(dp[z][y - 1][x],
                                      dp[z - 1][y - 1][x - weights[y - 1]] + values[y - 1])
                else:
                    dp[z][y][x] = dp[z][y - 1][x]

    return dp[-1][-1][-1]

w = 50000
k = 6
values = df['total_pts']
weights = df['cost']
n = len(values)

limit_fmt = 'Max value for weight limit {}, item limit {}: {}'

print(limit_fmt.format(w, k, knapsack2(n, w, k, values, weights))) 

我的输出:

              Driver  total_pts  cost
0  A.J. Allmendinger  29.030000  6400
1        Alex Bowman  39.189159  7600
2      Aric Almirola  53.746988  8800
3      Austin Dillon  32.476250  7000
4        B.J. McLeod  14.000000  4700

Max value for weight limit 50000, item limit 6: 325.00072048

我希望至少获得与最佳解决方案中的每个“ total_pts”相关联的“成本”,但是如果我可以将其绘制出数据框的“驱动程序”列来代替(我会猜测可以通过索引访问)。谢谢。

0 个答案:

没有答案