A travel blog shows its posts on a device with a fixed number of character columns. Turn a list of posts into the exact lines to display.
Write format_articles(articles: list[str], width: int) -> list[str].
Paragraphs and words. Inside an article, a paragraph break is a line that is empty or holds only spaces and tabs (so "\n\n" or "\n \n"). A word is a maximal run of non-whitespace characters. Single newlines, tabs and repeated spaces inside a paragraph are just word separators.
Wrapping (greedy, one paragraph at a time):
- Put words on the current line, separated by one space, as long as the line stays at most
widthcharacters. When the next word doesn't fit, start a new line with it. - A word longer than
widthis cut into pieces ofwidthcharacters (the last piece may be shorter), and the pieces are placed as if they were separate words. (So the first pieces each fill a line alone, and later words may follow the last piece.) - No line has leading or trailing spaces.
Output layout, as one flat list:
- Paragraphs of the same article are separated by one empty line
"". - Consecutive articles are separated by one line of
widthdashes,"-" * width. - Paragraphs without words and articles without words produce nothing at all (no empty lines, no extra separators). No separator comes before the first or after the last article shown.
format_articles(["Sunny beach house near the old harbour"], 12)
# ["Sunny beach", "house near", "the old", "harbour"]
format_articles(["Top five cafes\n\nOne: Lumen", "", "Supercalifragilistic view"], 10)
# ["Top five", "cafes", "", "One: Lumen",
# "----------",
# "Supercalif", "ragilistic", "view"]
In the second example the empty middle article is skipped, and Supercalifragilistic (20 letters) becomes two 10-letter pieces.
Constraints: 1 <= width <= 10^5, total text up to 10^6 characters. Aim for time linear in the total text.
Show hint
track the current line as a list of words plus its length. A word of length L fits if length + (1 if the line is non-empty else 0) + L <= width. Split paragraphs with re.split(r"\n[ \t]*\n", article) and words with str.split().