我有这个问题:“给定 n 个重量从 1 公斤到 10 公斤不等的物品,你如何在最少数量的袋子之间分配它们,知道每个袋子可能不超过 10 公斤。”。
我尝试通过将物品从最重到最轻分类来解决这个问题,如果它们合适则将它们放入一个袋子中,如果它们不合适则创建一个新袋子。如果是这种情况,则从剩余物品的最重到最轻重新开始。这是我的代码:
list_of_items=raw_input("Input the items' weights (separated by spaces): ").split()
for i in range(len(list_of_items)):
list_of_items[i]=int(list_of_items[i])
list_of_items.sort()
list_of_items.reverse()
while list_of_items[0]>=10:
list_of_items=raw_input("You have input an item wheighing over 10kg: ").split()
for i in range(len(list_of_items)):
list_of_items[i]=int(list_of_items[i])
list_of_items.sort()
list_of_items.reverse()
set_of_bags=[] #In this list we'll store the bags
while(len(list_of_items)!=0):
weight=0
bag=[] #creates a new bag
for item in list_of_items: #cycle copies items to bag
if item+weight<=10:
bag.append(item)
weight+=item
set_of_bags.append(bag) #adds bag to set_of_bags
for item in bag: #deletes the items that have been put in set_of_bags from original list
list_of_items.remove(item)
# output
n=0
for bag in set_of_bags:
n+=1
weight=0
for j in bag:
weight += j
print "bag #"+str(n), bag, "=>", weight, "kg."
我相信这给出了正确的答案,但我不知道如何证明它。有什么帮助吗?