← Back to problems
UNSW COMP2041 · hard

21T2 Q9 — Word wrap, in place

Args: a positive integer n (max line length) and a filename. Rewrite the file in place (print nothing):

  • lines ≤ n chars, or with no space → unchanged
  • n with a space in the first n chars → change the last such space to a newline

  • n with no space in the first n chars → change the first space on the line to a newline

Apply the rules recursively to newly created lines.


Python only; no external programs / subprocess. From COMP2041/9044 21T2 Final. Do not import textwrap.