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.
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to