I have a list of items: ShelvesToPack = [{'ShelfLength': 2278.0, 'ShelfWidth': 356.0, 'ShelfArea': 759152.0, 'ItemNames': 1}, {'ShelfLength': 1220.0, 'ShelfWidth': 610.0, 'ShelfArea': 372100.0, 'ItemNames': 2}, {'ShelfLength': 2310.0, 'ShelfWidth': 762.0, 'ShelfArea': 1760220.0, 'ItemNames': 3}, {'ShelfLength': 610.0, 'ShelfWidth': 610.0, 'ShelfArea': 1450435.0, 'ItemNames': 4}]
I have a certain criteria and I want to group the items based on those. I need the program that tells how many minimum number of groups one can have and how the items are grouped. I would like to form groups of these items such that (sum of shelflength (of itmes) <= max length or sum of shelfwidth (of items) <= max width) and sum of ShelfArea (of items) <= Max Area. In this case, if we look at the logic we can have all the items packed in minimum 2 groups - item 1 and 3 will form one group and item 2 & 4 will form other group. I would like to have the answer in the format: [[{'ShelfLength': 2278.0, 'ShelfWidth': 356.0, 'ShelfArea': 759152.0, 'ItemNames': 1} , {'ShelfLength': 2310.0, 'ShelfWidth': 762.0, 'ShelfArea': 1760220.0, 'ItemNames': 3}], [{'ShelfLength': 1220.0, 'ShelfWidth': 610.0, 'ShelfArea': 372100.0, 'ItemNames': 2}, , {'ShelfLength': 610.0, 'ShelfWidth': 610.0, 'ShelfArea': 1450435.0, 'ItemNames': 4}]] I have written a code but it does only one grouping ( need some help why it doesnot for the remaining items and what corrections need to be done) . ShelvesToPack_sorted=sorted(ShelvesToPack, key = itemgetter('ShelfWidth'), reverse = True) AreaOfObject= 2972897.28 current_width = 0 current_length = 0 current_area =0 shelf =[] shelves=[] if len(ShelvesToPack_sorted) > 0: for item in ShelvesToPack_sorted: if (current_width + item['ShelfWidth'] <= 1219.2 or current_length + item['ShelfLength'] <= 2438.5) and current_area + item['ShelfArea'] <= AreaOfObject: shelf.append(item) current_width += item['ShelfWidth'] current_length += item['ShelfLength'] current_area += item['ShelfArea'] del item if shelf: shelves.append(shelf) print(shelves) This produces only one grouping and does not group the remaining items. [[{'ShelfLength': 2310.0, 'ItemNames': 3, 'ShelfArea': 1760220.0, 'ShelfWidth': 762.0}, {'ShelfLength': 2278.0, 'ItemNames': 1, 'ShelfArea': 759152.0, 'ShelfWidth': 356.0}]] Can anyone please suggest? -- https://mail.python.org/mailman/listinfo/python-list