#177 · Strings · Expert · 210 XP · about 40 min
Newspaper columns stretch the spaces between words so that every line ends exactly at the right margin. Write justify(words, width) that lays out words in lines of width characters and returns the lines as a list of strings.
width characters by sharing the spaces between its gaps as evenly as possible. When they do not share out evenly, gaps further left get one more space than gaps further right.width.justify(["Python", "makes", "text", "layout", "a", "breeze"], 14) # returns ['Python makes', 'text layout a', 'breeze'] justify(["a", "b", "c", "d", "e"], 8) # returns ['a b c d', 'e'] justify(["Hi"], 10) # returns ['Hi']
In the first line, "Python" and "makes" use 11 characters, so the single gap gets all 3 spaces that are left. In the second line, 3 spaces are shared by 2 gaps: the left gap gets 2 and the right gap 1.
words has 0 to 1,000 items, and no words means no lines.width characters and contains no spaces.1 <= width <= 100Ready?
Accept the challenge to start writing. A small timer counts the time this page is in view.
Output appears here.