Need some suggestions in grouping of items
MRAB
python at mrabarnett.plus.com
Thu Sep 8 20:29:11 EDT 2016
On 2016-09-08 21:50, GP wrote:
>
> 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?
>
The easy way to do it is, in pseudocode:
shelves = []
while list_of_items:
shelf = []
# Also initialise width, length and area.
doesnt_fit = []
for item in list_of_items:
if item fits:
shelf.append(item)
# Also adjust width, length and area.
else:
doesnt_fit.append(item)
shelves.append(shelf)
list_of_items = doesnt_fit
More information about the Python-list
mailing list