Python用贪心算法解背包问题,运算结果很奇怪
Knapsack = 20.00
items = [
(1, "1", 2.44, 3.98),
(2, "2", 3.97, 1.71),
(3, "3", 4.02, 4),
(4, "4", 1.41, 1.55),
(5, "5", 3.35, 3.65),
(6, "6", 3.46, 1.78),
(7, "7", 1.19, 2.7),
(8, "8", 4.64, 1.04),
(9, "9", 4.53, 3.11),
(10, "10", 4.17, 0.2) ]
AfterSorted = sorted(((profit/ItemWeight, ItemWeight, ItemName)
for itemno, ItemName, ItemWeight, profit in items), reverse = True)
Weight = Value = 0
Knapsacked = []
for unit_Valueue, ItemWeight, ItemName in AfterSorted:
portion = min(Knapsack - Weight, ItemWeight)
Weight += portion
addValue = portion * unit_Valueue
Value += addValue
Knapsacked += [(ItemName, portion, addValue)]
if Weight >= Knapsack:
break
print(" Item Name ItemWeight Profit")
print("\n".join("%13s %20.2f %16.2f" % item for item in Knapsacked))
print("\nItemWeight in total: %5.2f\nValueue in total: %5.2f" % (Weight, Value))
以上是我的代码,用贪心算法,取物品取到应该接近20,然后多余的背包容量不应该继续填充,结果我的程序跑出来以后,会把其中一个物品的部分容量给弄出来塞进包里,最后结果还是20KG,本来应该只有16.94KG的
不符合我的题目的要求,求指点修改,谢谢大家