如何解决如何打印添加的项目 ID 动态编程背包 Python
我在一篇中等文章中找到了这个背包问题的例子。我添加了一组 Id 我想要做的是添加与已添加的值相对应的 id。例如:
saved_ids = [first_value_id,second_value_id,....]
非常感谢任何帮助。
def solve_knapsack(profits,weights,capacity):
saved_ids = []
n = len(profits)
if capacity <= 0 or n == 0 or len(weights) != n:
return 0
dp = [[0 for x in range(capacity+1)] for y in range(n)]
# populate the capacity = 0 columns,with '0' capacity we have '0' profit
for i in range(0,n):
dp[i][0] = 0
# if we have only one weight,we will take it if it is not more than the capacity
for c in range(0,capacity+1):
if weights[0] <= c:
dp[0][c] = profits[0]
for i in range(1,n):
for c in range(1,capacity+1):
profit1,profit2 = 0,0
if weights[i] <= c:
profit1 = profits[i] + dp[i-1][c-weights[i]]
profit2 = dp[i][c]
dp[i][c] = max(profit1,profit2)
# print(weights[i])
print(dp[i-1][c-1])
# saved_ids =
# maximum profit will be at the bottom-right corner.
print(dp)
return dp[n-1][capacity]
驱动程序代码
items = ["A","B","C","D"]
weights = [2,3,1,4]
profits = [4,5,7]
capacity = 5
print(solve_knapsack(profits,capacity))
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。