Batching
Please Log In for full access to the web site.
Note that this link will take you to an external site (https://shimmer.mit.edu) to authenticate, and then you will be redirected back to this page.
As an intern for Yielding Unique Macarons (YUM), you've been tasked with assigning the orders that YUM fulfills in each batch of cookies its factory makes. Because space in the factory is limited, each batch of cookies must be immediately packed and shipped. Due to the higher costs associated with fulfilling a single order through sending multiple shipments to the same location, YUM wants to experiment with fulfilling orders in a single batch, even if it means that the factory sometimes make fewer boxes than it is capable of.
To help accomplish this, complete the batch
function according to the problem description below:
def batch(inp, size):
"""
Inputs:
inp (tuple<int>) - a tuple of non-negative integers representing the
number of boxes of cookies in each order.
size (int) - a non-negative integer that represents the maximum boxes
of cookies that the factory can produce in a single batch.
Returns:
A list of batches, where each batch is a list of elements
from "inp" (in the same order as from "inp"), with just
enough elements to fill the batch. A batch is filled when the
sum of the values of the elements in the batch is less than or
equal to "size," or when there are no more elements from "inp" to
put in the batch.
Ex: batch((1,2,3), 3) results in two full batches [[1, 2], 3]
but batch((1,3,2), 3) results in three batches [[1], [3], [2]]
For simplicity, you can assume that a single order will
NOT exceed the max batch size.
"""
pass # your code here
if __name__ == "__main__":
res1 = batch((2, 3, 4, 3, 1, 1, 1, 4, 2, 3), 5)
exp1 = [[2, 3], [4], [3, 1, 1], [1, 4], [2, 3]]
print(f"batch((2, 3, 4, 3, 1, 1, 1, 4, 2, 3), 5)\n Got {res1}\n Exp {exp1}")
res2 = batch((6, 7, 6, 1, 6), 7)
exp2 = [[6], [7], [6, 1], [6]]
print(f"batch((6, 7, 6, 1, 6), 7)\n Got {res2}\n Exp {exp2}")
res3 = batch((4, 4), 4)
exp3 = [[4], [4]]
print(f"batch((4, 4), 4)\n Got {res3}\n Exp {exp3}")
To clarify, we make the batch by adding in elements from the input tuple until the batch reaches the size
amount. Then we stop that batch and begin the next one.
For example, what should be the returned value of the call batch((1, 7, 3, 4, 3, 2, 4, 3), 9)
be?
Our first batch starts with the first order of 1. The next order is 7, and
adding 7 to the current batch of 1 is under our cap of 9, so we can add it to
the first batch. Adding the next order 3 + 1 + 7 would exceed 9, so the first
batch is finished with 1 and 7, and we start a new batch with just 3 in it. We
continue the process until we get our answer [[1, 7], [3, 4], [3, 2, 4], [3]]
.
Next Exercise: Read States