我有一个函数,它可以确定填充容量为200的堆栈的最佳方式。 要求如下:
capacity = 200
dairy_items=[('p1', 10, 3), ('p2', 13, 5),
('p3', 15, 2), ('p4', 26, 2),
('p5', 18, 6), ('p6', 25, 3),
('p7', 20, 4), ('p8', 10, 5),
('p9', 15, 4), ('p10', 12, 7),
('p11', 19, 3), ('p12', 27, 6),
('p13', 16, 4), ('p14', 23, 5),
('p15', 14, 2), ('p16', 23, 5),
('p17', 12, 7), ('p18', 11, 3),
('p19', 16, 5), ('p20', 11, 4)]
第一个元组元素是唯一的产品id,第二个是产品大小,第三个是价格
所以我创建了这个函数。我只有一个问题。堆叠的第一件东西是产品p8,因此需要从dairy_项中删除此项,以便函数不会再次选择该值,因为它已被使用。我用dairy_items.remove()尝试了这个方法,但不起作用。是否有其他方法可以使用,或者我只是没有正确使用
def shelving(dairy_items):
filled = 0
worth = 0
shelves = []
while filled <= capacity:
smallest_product = math.inf
most_expensive_product = 0
for productNr in range(len(dairy_items)):
if dairy_items[productNr][1] < smallest_product:
smallest_product = dairy_items[productNr][1]
most_expensive_product = dairy_items[productNr][2]
productID = dairy_items[productNr][0]
elif smallest_product == dairy_items[productNr][1]:
if dairy_items[productNr][2] > most_expensive_product:
smallest_product = dairy_items[productNr][1]
productID = dairy_items[productNr][0]
filled = filled + smallest_product
worth = worth + most_expensive_product
shelves.append(productID)
dairy_items.remove((productID, smallest_product, most_expensive_product))
return (shelves,filled,worth)
问题是
elif
块没有分配most_expensive_product
。因此,您可以在if
块中分配most_expensive_product
,在elif
块中分配smallest_product
和productID
。这将导致在remove
调用中构造一个元组,该元组一开始就不存在,因此无法删除您可以通过在
elif
中添加赋值来解决这个问题,假设这是您的期望行为我对您的变量名有点困惑,因为
most_expensive_product
似乎不是最昂贵的产品,而是最小产品的价格(或者如果有多个最小的项目,则价格更高)如果我对您尝试执行的操作的假设是正确的,那么使用for循环会更好,这样您就避免了在索引和元组重建方面的麻烦。例如,下面的内容似乎与您的意图相符:
然而,这仍然有一个问题,您的原始代码有;因为它只在循环开始时检查容量,所以它会将货架填满。这可以通过在末尾添加支票来解决,如下所示:
我的代码中有一些愚蠢的错误。我改变了一些事情,下面的事情对我来说是可行的
相关问题 更多 >
编程相关推荐