title: Grouping values from list into buckets to keep sum of values at or below threshold
body: <p>I have a list of times in minutes that represent the time it takes to do some job, but the amount of time spent working cannot exceed 240 minutes in any given day.I would like to separate into N groups such that the sum of the items in the group does not exceed the threshold (240 in this example).</p>
  <p>An example list could be <code>[60, 70, 90, 120, 180, 240]</code></p>
  <p>One possible solution to the above list would be:
  <code>[[240], [180, 60], [70, 90], [120]]</code>. Note how each of the sums in each list does not exceed the threshold of 240 while leaving some leftover is fine, but how do I know this is the most optimal solution? Optimal being defined as simultaneously minimizing leftover and the number of buckets.</p>
  <p>I've been working on trying to do this with some <code>for</code> loops in Python but it feels about as inefficient as possible. Also, due to the method of removing items from the list, the <code>for</code> loop isn't iterating over all values. Below is my attempt.</p>
  <pre><code>import random
  import math
  
  def roundup(x):
      return int(math.ceil(x / 10.0)) * 10
  
  threshold = 240;
  
  randomlist = []
  
  for i in range(0,10):
      n = random.randint(30,240)
      randomlist.append(roundup(n))
  
  days = []
  
  print (randomlist)
  
  for item in randomlist:
      schedule = []
      schedule.append(item)
      minutes_remaining = threshold - item
      for item2 in randomlist:
          if randomlist.index(item) != randomlist.index(item2):
              if item2 &lt;= minutes_remaining:
                  minutes_remaining -= item2
                  schedule.append(item2)
                  randomlist.remove(item2)
      randomlist.remove(item)
      days.append(schedule)
  
  print (days)
  </code></pre>