hello i have a real world problem to solve. i have list of woods lengths (in cm). i want to put them in boxes each box has 4 rows , we can put woods in a row as long as the total length doesn't exceed 140 cm. but there is an exception if one wood is longer than 140 cm we can put it in an empty row. i need to return 3 thing from my function:
my function works for the first box , but when box is full and i reset the box inside my function and call itself again something cause an issue and the outcome is none or false.
my_woods = [50, 60, 70, 40, 30, 120, 90, 50, 70, 70, 60, 30, 45, 25, 40, 45, 150, 60, 70, 80, 25, 40, 80]
row_length = 140
box = [[], [], [], []]
box_idx = 1
def addtobox(length, box, box_idx):
for idx, row in enumerate(box):
if row == []:
row.append(length)
return idx, sum(row) - length, box_idx
else:
sum_row = sum(row)
if row_length - sum(row) >= length:
row.append(length)
return idx, sum(row) - length , box_idx
box = [[], [], [], []]
box_idx += 1
addtobox(length, box, box_idx)
for wood in my_woods:
print(addtobox(wood, box, box_idx))
# Result
# (0, 0, 1)
# (0, 50, 1)
# (1, 0, 1)
# (1, 70, 1)
# (0, 110, 1)
# (2, 0, 1)
# (3, 0, 1)
# (3, 90, 1) # the last correct result
# None
# None
# None
# (1, 110, 1)
# None
# None
# None
# None
# None
# None
# None
# None
# None
# None
# None
MAYBE you can try something like change, inside your function , this:
box = [[], [], [], []]
into this:
box.clear()
box = [[], [], [], []]
Hope it can help
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.