Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>This algorithm relies on assumption that if we know optimal solution for the N-1,N-2,..,2,1 last words in the text then it is easy to construct optimal solution for N words. Memorization allows to avoid recomputing results of <code>best_partition()</code> calls for the same input: </p> <pre><code>import functools def wrap(text, width): """ &gt;&gt;&gt; wrap('This is a sample text', 7) ['This', 'is a', 'sample', 'text'] """ return [' '.join(line) for line in best_partition( tuple(text.split()), functools.partial(cost, width=width))] def best_partition(words, cost): """The best partition of words into lines according to the cost function.""" best = [words] # start with all words on a single line for i in reversed(range(1, len(words))): # reverse to avoid recursion limit lines = [words[:i]] + best_partition(words[i:], cost) if cost(lines) &lt; cost(best): best = lines return best def memoize(func): cache = {} @functools.wraps(func) def wrapper(*args): try: return cache[args] except KeyError: ret = cache[args] = func(*args) return ret return wrapper best_partition = memoize(best_partition) </code></pre> <p>Where <code>cost()</code> is:</p> <pre><code>def linelen(words): """Number of characters in a line created from words.""" if not words: return 0 # words + spaces between them return sum(map(len, words)) + len(words) - 1 def cost(lines, width): """ - each line except last costs `(width - w)**3`, where `w` is the line width - cost is infinite if `w &gt; width` and the line has more than one word &gt;&gt;&gt; cost([['a'], ['b']], 1) 0 &gt;&gt;&gt; cost([['a','b']], 1) inf &gt;&gt;&gt; cost([['a'], ['b']], 3) 8 &gt;&gt;&gt; cost([['a', 'b']], 2) inf """ if not lines: return 0 s = 0 for i, words in enumerate(lines, 1): w = linelen(words) if width &gt;= w: if i != len(lines): # last line has zero cost s += (width - w)**3 elif len(words) != 1: # more than one word in the line return float("inf") # penalty for w &gt; width return s </code></pre> <h3>Example:</h3> <pre><code>print('\n'.join(wrap(""" In olden times when wishing still helped one, there lived a king whose daughters were all beautiful, but the youngest was so beautiful that the sun itself, which has seen so much, was astonished whenever it shone in her face. Close by the king's castle lay a great dark forest, and under an old lime-tree in the forest was a well, and when the day was very warm, the king's child went out into the forest and sat down by the side of the cool fountain, and when she was bored she took a golden ball, and threw it up on high and caught it, and this ball was her favorite plaything. """, int(sys.argv[1]) if len(sys.argv) &gt; 1 else 70))) </code></pre> <h3>Output</h3> <pre>In olden times when wishing still helped one, there lived a king whose daughters were all beautiful, but the youngest was so beautiful that the sun itself, which has seen so much, was astonished whenever it shone in her face. Close by the king's castle lay a great dark forest, and under an old lime-tree in the forest was a well, and when the day was very warm, the king's child went out into the forest and sat down by the side of the cool fountain, and when she was bored she took a golden ball, and threw it up on high and caught it, and this ball was her favorite plaything.</pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload