Suggestions to improve a code
GP
gyan.am010 at gmail.com
Tue Sep 6 10:55:20 EDT 2016
I have a list:
shelves2 =[{'Part No': '1', 'Length': 610.0, 'Width': 50.0},
{'Part No': '2', 'Length': 2319.0, 'Width': 465.0 },
{'Part No': '3', 'Length': 5.0,'Width': 465.0}]
The length of shelf is calculated as follows:
1. Calculate the maximum length of all items in the shelf.
2. Calculate width of shelf = 610 (in this case).
3. Length of shelf : maxlength of all items + length ( if it less than width of shelf) or width of other items such that length of shelf is less than maximum allowed length.
In the above case the length is 2319+50+5 = 2374. I have the following code which generates it correctly but would like to know if there is a better way to write it. I would like to know some smarter way to write the code ( especially if the "for", "if" statements can be avoided).
list_1=[]
list_2=[]
WidthOfShelf = max([x['Width'] for x in shelves2])
MaxLengthOfItem = max([x['Length'] for x in shelves2])
f_LMax=lambda seq, m: [ii for ii in range(0, len(seq)) if seq[ii] ['Length'] >= m][0]
MaxLengthOfItem_Index =f_LMax(shelves2,MaxLengthOfItem)
current= MaxLengthOfItem
list_1=[shelves2[MaxLengthOfItem_Index]]
list_2 = [MaxLengthOfItem]
del shelves2[MaxLengthOfItem_Index]
for i in range(0,len(shelves2)):
if shelves2[i]['Length'] <= Width:
if (current + shelves2[i]['Length']) or (current + shelves2 [i]['Width'])<= 2438.5 :
q_2= min(shelves2[i]['Length'], shelves2[i]['Width'])
q=shelves2[i]
list_1.append(q)
list_2.append(q_2)
current += (shelves2[i]['Length'] or shelves2[i] ['Width'])
length = sum(list_2)
print("LENGTH:",length)
More information about the Python-list
mailing list