Suppose you have some text consisting of $ n $ words and you want to arrange them in order into $ L $ lines. What is the best way to do this? As a rule of thumb you want to avoid making the text look unbalanced. No line should be significantly longer than another line.
We can turn this into an algorithm design problem. If the goal is to make the lines balanced, we can optimize the ratio of the length of the longest line to the length of the shortest line. A ratio of exactly 1 would mean that all lines have equal length, and a ratio of 1.2 would look decent.
How can we find the arrangement of words that gives us the optimal ratio? We want a function that accepts a number of lines and a list of words (or their lengths), and returns the best arrangement of those words:
def arrange_words(L, wordlengths, space_size): ...
space_size parameter is the width of the space between words in a line. I recommend ignoring it at first. I will say no more if you want to solve this problem yourself, but I have written my own solution and posted it on github here.