efficient way of splitting a list in to lists where the sum of the values in each does not exceed n

Tom Boland tom at t0mb.net
Wed Nov 24 10:34:52 EST 2010


I'm trying to find a _nice_ way of taking a list of integers, and 
splitting them in to lists where the sum of the values does not exceed a 
threshold.

for instance:

l = [1, 2, 3, 4, 5, 6]
n = 6

nl = [1,2,3], [4], [5], [6]


I don't mind if it's done like playing blackjack/pontoon (the card game 
where you try not to exceed a total of 21), ie. going through the list 
sequentially, and splitting off the list as soon as the running total 
would exceed n.  A way of efficiently making all lists as close to n as 
possible would be nice however.

I have an algorithm, but it's very ugly. I don't want to paste it, as 
it's a bit more complicated than I have made out, and wouldn't make too 
much sense out of context.  It's a very ugly blight on my code as well! 
I wonder if anyone out there has some crazy one-line list comprehension 
or idiomatic way of doing this beautifully :)


Many thanks.  Tom.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20101124/3eccbc6c/attachment.html>


More information about the Python-list mailing list