gpt4 book ai didi

python - 使用贪心Python算法解决背包问题

转载 作者:行者123 更新时间:2023-12-01 01:32:52 24 4
gpt4 key购买 nike

我正在尝试使用Python解决背包问题,实现贪婪算法。我得到的结果对我来说毫无意义。

背包:

第一行给出了元素的数量,在本例中为 20。最后一行给出了背包的容量,在本例中为 524。其余行给出了每个元素的索引、值(value)和重量。

20
1 91 29
2 60 65
3 61 71
4 9 60
5 79 45
6 46 71
7 19 22
8 57 97
9 8 6
10 84 91
11 20 57
12 72 60
13 32 49
14 31 89
15 28 2
16 81 30
17 55 90
18 43 25
19 100 82
20 27 19
524

Python 代码:

import os 

def constructive():
knapsack = []
Weight = 0
while(Weight <= cap):
best = max(values)
i = values.index(best)
knapsack.append(i)
Weight = Weight + weights[i]
del values[i]
del weights[i]
return knapsack, Weight


def read_kfile(fname):
with open(fname, 'rU') as kfile:
lines = kfile.readlines() # reads the whole file
n = int(lines[0])
c = int(lines[n+1])
vs = []
ws = []
lines = lines[1:n+1] # Removes the first and last line
for l in lines:
numbers = l.split() # Converts the string into a list
vs.append(int(numbers[1])) # Appends value, need to convert to int
ws.append(int(numbers[2])) # Appends weigth, need to convert to int
return n, c, vs, ws

dir_path = os.path.dirname(os.path.realpath(__file__)) # Get the directory where the file is located
os.chdir(dir_path) # Change the working directory so we can read the file

knapfile = 'knap20.txt'
nitems, cap, values, weights = read_kfile(knapfile)
val1,val2 =constructive()
print ('knapsack',val1)
print('weight', val2)
print('cap', cap)

结果:

knapsack [18, 0, 8, 13, 3, 8, 1, 0, 3]
weight 570
cap 524

最佳答案

欢迎。您的程序给出的重量超过上限的原因是因为在您放入背包中的最后一个元素上,您没有检查它是否可以放入背包中。为此,只需添加一个 if 语句,此外您还应该检查值列表是否为空。请注意,我添加了 (i+1),因为文本文件的索引从 1 开始,但 Python 的列表索引从 0 开始:

def constructive():
knapsack = []
Weight = 0

while(Weight <= cap and values):
best = max(values)
i = values.index(best)
if weights[i] <= cap-Weight:
knapsack.append(i+1)
Weight = Weight + weights[i]
del values[i]
del weights[i]

return knapsack, Weight

关于python - 使用贪心Python算法解决背包问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52672806/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com