Justify Text to a Fixed Width

medium
Unit 16 · Strings IV0/3 to milestone

Lay out words into lines of exactly width characters, like a newspaper column.

Implement justify(words, width):

  • Pack as many words as fit on each line (greedily), with at least one space between words.
  • Distribute extra spaces between words as evenly as possible. When they don't divide evenly, the left gaps get more.
  • The last line and any line with a single word are left-aligned and padded with spaces on the right.
  • Raise ValueError if any word is longer than width.
#strings#formatting#greedy2 visible + 2 hidden tests
solution.py · Python 3.13
Loading editor…
Run your code to see results. ⌘↵ to run · ⌘⇧↵ to submit
Justify Text to a Fixed Width · TechGradify