Batching

The questions below are due on Sunday July 06, 2025; 10:00:00 PM.
 
You are not logged in.

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.

To help accomplish this, write a function called batch according to the problem description below:

The batch function has two parameters:

  • orders is a tuple of non-negative integers representing the number of boxes of cookies in each order. For example, (1, 2, 3) represents 3 orders of cookies, where the first order is for 1 box, the second order is for 2 boxes, and the third order is for 3 boxes.
  • size_limit is a positive integer that represents the maximum boxes of cookies the factory can produce in a single batch. For simplicity, you can assume that size_limit >= the largest single order in orders.

batch should return a list of batches, where each batch is a list of numbers from orders (in the same order) that is as close to reaching the maximum batch size_limit as possible.

For example, batch((1, 2, 3), 3) should result in [[1, 2], [3]], which represents two full batches. The first batch [1, 2] fulfills the first two orders and reaches the size_limit, so we need a second batch [3] in order to fulfill the third order.

Note that batch((1, 3, 2), 3) should result in three batches [[1], [3], [2]] because YUM is experimenting with a first-come first-serve policy. So the first order 1 can fit in the first batch [1]. Because adding 3 to the first batch would create a batch of 4 boxes, which exceeds the size_limit, 3 gets added to a separate second batch [3]. Because the second batch is full, we start a third batch that the 2 order gets added to, which is then completed as [2] because there are no remaining orders.

Following a similar logic, calling batch((1, 1, 3, 2, 2, 1), 3) should result in [[1, 1], [3], [2], [2, 1]].

Now implement the batch function and upload it in a file below. You may find the following test cases useful as you complete the batch function:

if __name__ == "__main__":
    # feel free to add additional tests of your own!
    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}")

  No file selected

Next Exercise: 100 Doors

Back to exercises