Classic Python exam exercise: wrap a text into subtitle lines using functions, lists and strings, with graded hints and a tested reference solution.
Updated on
Exam Code Python Programming fundamentals Exam level Tested code

A university lecture-capture platform needs to generate subtitles for its recorded lectures. Each subtitle line holds at most W characters, and the text must be distributed over lines keeping words intact whenever possible. Write a Python program that performs this wrapping.
Input (standard input). The first line contains an integer W with 2 ≤ W ≤ 60. Everything after it, which may span several lines or none at all, is the text. A word is any maximal sequence of non-whitespace characters; the line breaks and repeated spaces of the original text do not matter.
Wrapping rules. (1) Any word longer than W is broken into pieces: every piece except the last consists of the next W-1 characters of the word followed by a hyphen -; the last piece is whatever remains, which is then at most W long. (2) Words (or pieces), which we call tokens, are placed in order and greedily: a token is appended to the current line, separated by a single space, if the resulting length does not exceed W; if it does not fit, the current line is closed and the token starts a new line.
Output (standard output). Each line of the result is printed preceded by its number with at least two digits (zero-padded), a colon and a space, for instance 03: text. Then print one summary line in the format Lines: N, fill: P%, where N is the number of lines and P is the integer percentage, truncated, of characters used with respect to the capacity N·W. If the text contains no words at all, print only No text.
Organise your solution into functions: at least split_word(word, width), which returns the list of pieces of one word, and wrap(text, width), which returns the list of lines. Do not use the textwrap module.
Sample input
10
An electroencephalogram runs
again in room 3Expected output
01: An
02: electroen-
03: cephalogr-
04: am runs
05: again in
06: room 3
Lines: 6, fill: 71%- Function split_word: correctly breaks words longer than the width, with a hyphen and without an infinite loop
- 0.75
- Function wrap: greedy placement of words into lines without exceeding the width and without losing the last line
- 1.0
- Reading the input and exact output format (numbering, summary line and truncated percentage)
- 0.5
- Edge cases: empty or whitespace-only text, word of exactly the width, minimum width
- 0.25
Hints
Hint 1 · How many different situations arise when placing a token?
Keep a string current holding the line you are building. For each token there are only three situations: the line is empty, the token fits (current length + 1 space + token length ≤ W), or it does not fit. When it does not fit, store current in the list and start a new one. Do not forget whatever is left in current when the loop ends.
Hint 2 · Do long words need special handling inside the wrapping loop?
Look at the length of a hyphenated piece: W-1 characters plus the hyphen. That is exactly W, so it can never share a line with anything else. If you first turn every word into its list of pieces and then wrap all the pieces as if they were ordinary words, the greedy rule does the rest without a single extra if.
Hint 3 · How do you break a word without messy indices?
Use a loop while len(word) > width that cuts with slices: the piece is word[:width - 1] + "-" and the word becomes word[width - 1:]. When the loop exits, what remains is the last piece. Convince yourself that the loop terminates: what would happen if width - 1 == 0?
Solution
Explained solution
The solution separates three responsibilities into small functions: reading the input, breaking long words and wrapping the tokens into lines. A fourth function computes the fill percentage. Each piece can then be reasoned about and tested on its own, which is exactly what the rubric rewards.
The key idea is to first convert the text into a flat list of tokens (ordinary words and pieces of long words) and then apply one single greedy pass over that list. Two separate, simple steps are much easier to get right under exam pressure than one loop that tries to do everything.
import sys
def read_input(data):
"""Separate the width (first line) from the rest of the text."""
parts = data.split("\n", 1)
width = int(parts[0])
text = parts[1] if len(parts) > 1 else ""
return width, text
def split_word(word, width):
"""Return the list of pieces of a word; none is longer than width."""
pieces = []
while len(word) > width:
pieces.append(word[:width - 1] + "-")
word = word[width - 1:]
pieces.append(word)
return pieces
def wrap(text, width):
"""Distribute the text over lines of at most 'width' characters."""
tokens = []
for word in text.split():
tokens.extend(split_word(word, width))
lines = []
current = ""
for token in tokens:
if current == "":
current = token
elif len(current) + 1 + len(token) <= width:
current += " " + token
else:
lines.append(current)
current = token
if current:
lines.append(current)
return lines
def fill_percent(lines, width):
"""Integer (truncated) percentage of characters used."""
used = sum(len(line) for line in lines)
return 100 * used // (len(lines) * width)
def main():
width, text = read_input(sys.stdin.read())
lines = wrap(text, width)
if not lines:
print("No text")
return
for n, line in enumerate(lines, start=1):
print(f"{n:02d}: {line}")
print(f"Lines: {len(lines)}, fill: {fill_percent(lines, width)}%")
main()read_input uses split("\n", 1) to cut only at the first line break: the left part is the width and the right part is the whole text, however many lines it spans. If the input contains nothing but the number, as in the test case "width only", the right part is empty or missing and the text ends up as an empty string. int tolerates surrounding spaces and a trailing \r, so the first line needs no cleaning.
split_word trims the word with slices while it is longer than width. Each iteration appends word[:width - 1] + "-" and advances width - 1 characters. In the example, with W = 10, the word electroencephalogram (20 characters) produces electroen-, cephalogr- and am. A word of exactly W characters never enters the loop and comes out as a single piece; the test "exact word and word one too long" checks this, where abcde stays whole and abcdef becomes abcd- and ef.
wrap gets the words with text.split() without arguments, which splits on any run of spaces, tabs or newlines and discards empty strings. That is why the double space in the example produces no empty word and the "spaces only" case ends with an empty list. extend adds every piece of each word to tokens individually; using append would insert the whole list as a single element, which is a classic bug.
The loop over tokens implements the three situations from the first hint. The condition len(current) + 1 + len(token) <= width counts the separating space; forgetting that + 1 is the most frequent mistake. In the second test, the line nine in the main is exactly 16 characters and is accepted because the comparison is <=, not <. After the loop, if current: stores the last line, which would otherwise be lost silently.
Hyphenated pieces need no special treatment: they measure exactly W, so if current is not empty they do not fit with it, and the following token cannot fit next to them either. In the example, An closes on its own as line 01 because electroen- cannot follow it, while the final piece am is short and does combine afterwards with runs on line 04.
fill_percent adds up the line lengths and applies integer division // to the product 100 * used, which truncates without ever going through floating point. In the example 43 of 60 characters are used: the exact value is 71.67, so the program prints 71, not 72. Finally, main numbers the lines with enumerate(..., start=1) and the format spec {n:02d}, and prints No text when wrap returns an empty list.
Step-by-step trace · generated by running the code
| Step | token | current | lines |
|---|---|---|---|
| 1 | An | An | 0 |
| 2 | electroen- | electroen- | 1 |
| 3 | cephalogr- | cephalogr- | 2 |
| 4 | am | am | 3 |
| 5 | runs | am runs | 3 |
| 6 | again | again | 4 |
| 7 | in | again in | 4 |
| 8 | room | room | 5 |
| 9 | 3 | room 3 | 5 |
Test cases
| Case | Input | Expected output | Actual output | Result |
|---|---|---|---|---|
| example with a long word and text on two lines | 10
An electroencephalogram runs
again in room 3 | 01: An
02: electroen-
03: cephalogr-
04: am runs
05: again in
06: room 3
Lines: 6, fill: 71% | 01: An
02: electroen-
03: cephalogr-
04: am runs
05: again in
06: room 3
Lines: 6, fill: 71% | OK |
| ordinary sentence with an exactly full line | 16
The programming exam starts at nine in the main lecture hall | 01: The programming
02: exam starts at
03: nine in the main
04: lecture hall
Lines: 4, fill: 89% | 01: The programming
02: exam starts at
03: nine in the main
04: lecture hall
Lines: 4, fill: 89% | OK |
| spaces only | 12
| No text | No text | OK |
| exact word and word one too long | 5
abcde abcdef | 01: abcde
02: abcd-
03: ef
Lines: 3, fill: 80% | 01: abcde
02: abcd-
03: ef
Lines: 3, fill: 80% | OK |
| minimum width | 2
abc x y | 01: a-
02: bc
03: x
04: y
Lines: 4, fill: 75% | 01: a-
02: bc
03: x
04: y
Lines: 4, fill: 75% | OK |
| width only | 7 | No text | No text | OK |
Actual outputs: code compiled with Python 3.13.16 and run in an isolated container on 17 November 2026.
Complexity
Let L be the total length of the text. split scans the text once. split_word uses slices that copy the remaining word on every iteration; for a word of length m that costs O(m²/W) in the worst case, which is negligible for realistic words and W ≥ 2. It can be brought down to O(m) by walking an index along the word instead of reassigning word.
In wrap, the concatenation current += " " + token copies the line, but a line never exceeds W characters, so each token costs O(W) and the total is O(L·W), that is, linear in the text for a bounded width. Memory is O(L): the token list and the line list together hold each character of the text a constant number of times.
Common mistakes
- Forgetting the separating space when checking whether a token fits, writing
len(current) + len(token) <= width, which produces lines ofW + 1characters. - Not appending the last line after the loop: the program prints every line except the final one and the summary reports one line fewer.
- Using
split(" ")instead ofsplit(): double spaces create empty words and newlines stay glued to the words. - Cutting pieces of
Wcharacters plus the hyphen, producing tokens of lengthW + 1that never fit on any line. - Computing the percentage with
round, or with/and the format:.0f, which rounds instead of truncating and prints 72 where 71 is expected in the example. - Using
appendinstead ofextendwhen collecting pieces, which nests lists inside the token list.
Variants
Right-align or centre each line
Only the printing changes: line.rjust(width) or line.center(width) pads with spaces up to W. The wrapping itself is untouched. Ask whether padding spaces count towards the fill percentage; with the definition in the statement they should not, so call fill_percent on the unpadded lines.
Fully justify the text by distributing the gaps
For every line except the last, compute the missing spaces, W - len(line), and spread them over the k - 1 gaps between its k words with divmod: every gap gets the quotient and the first ones get one extra until the remainder is used up. Single-token lines stay as they are. Rebuilding a line requires its list of words, so it is easier if wrap returns lists of tokens instead of strings. The same accumulate-and-flush pattern appears in streaks and maximum in a list in Python.
Group lines into two-line captions
A real subtitle shows two lines at a time. With the list already computed, iterate over range(0, len(lines), 2) and take lines[i:i + 2]; slicing works even when the last pair is incomplete.
On the syllabus
The skills drilled here, decomposing a problem into small functions and manipulating strings, are part of the syllabus of Stanford's CS106A Programming Methodology, whose lecture list covers function calls and decomposition, while loops, booleans and strings. At Carnegie Mellon's 15-122 Principles of Imperative Computation the course description lists arrays, while and for loops and functions, the imperative building blocks that this exercise uses through Python lists and loops.
More briefly, the syllabus of Programación at UNAM's Facultad de Ciencias includes a unit on structured data, and the Fundamentos de Programación programme at IPN (ISC 2020) lists functions and structured data types among its contents.
Article generated with AI.larebelion



Comments (0)
No comments yet. You can be the first.
Write a comment