贪心算法(又称贪婪算法)是指,在对问题求解时,总是做出在当前看来是最好的选择。也就是说,不从整体最优上加以考虑,他所做出的是在某种意义上的局部最优解。通俗一点讲,当要解决某一个问题时,先判断第一步的最优解,然后把剩下的步骤看作下一个递归的具体问题。
代码实现:
if __name__ == "__main__":
beg = 50
value = 0
choice = []
while beg > 0:
if beg >= 8:
beg = beg - 8
value += 13
choice.append("B")
elif beg >= 10:
beg = beg - 10
value += 15
choice.append("C")
elif beg >= 6:
beg = beg - 6
value += 8
choice.append("A")
else:
break
print("背包剩余空间为"+str(beg))
print("背包中放置的物品为")
print(choice)
代码运行结果:
背包剩余空间为2
背包中放置的物品为
['B', 'B', 'B', 'B', 'B', 'B']