你好,看了你的代码和注解真的受益匪浅,再次感谢!
我后来参考了网上的一些代码,自己用Python解了一下这个程序,以下是我的代码,不知道你懂不懂Python,如果懂的话帮我看看。
我貌似解出来以后,运算结果和Prolog的有点不一样,你帮我看下是怎么回事,我算出来正好20呢?
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))
另外不知道你是否懂Haskell,我还需要用Haskell来解这个程序,同样的算法,哎,实在是没头绪