Meet the returns desk
A college library has a returns desk. Students bring books back, a volunteer scans each one, and the desk keeps a slip for every return. A slip is one line of text:
B10422 asha 3
That is the book's accession number, the borrower's login and the number of days late. Zero means on time. Over a term the desk collects tens of thousands of slips, and somebody has to answer questions about them. Which borrowers owe a fee? Which three-day stretch was the busiest? Is this book code already in the pile? Is the search box's bracket expression even valid?
This track builds one small Python program, desk.py, that answers those questions. Every chapter adds a piece. You will meet lists, dictionaries and sets, then the patterns that make a slow answer fast: windows that slide, maps that remember, stacks, recursion, trees, binary search and sorting. The desk is the only example. By the end you will have seen each idea solve a real part of the same program, which is how you learn to spot an idea when it turns up wearing different clothes.
Examples are in Python. The ideas are the same in JavaScript, Java or C++. Python is the language here because it has the least ceremony: a list is [], a dictionary is {}, and a function is three lines. If you already write another language well, keep writing it. Pick one language and get fluent in it, rather than knowing three at a shallow level. Fluent means you can type a loop, a function and a dictionary lookup without stopping to think about the syntax. That frees your attention for the problem, which is where it belongs.
This chapter is about the part that happens before any code. The habit it teaches takes about two minutes per problem and saves far more than that.
Read the problem twice before you type
Here is what goes wrong when you skip this. You read half a problem, recognise something, and start typing the solution to the problem you think you saw. Ten minutes later a test fails on an input you never considered, and you discover the problem asked for something slightly different.
The fix is boring and it works. Read the whole statement once. Then read it again, and this time say it back in your own words, out loud or in a comment at the top of your file.
Every example in this track was run on Python 3.13; a newer version may word an error message a little differently.
Try it on the desk's first question. The library wants a fee report. The rule is: a return that is late by more than 7 days owes a fee of 2 rupees per day late, counting every day, not only the days past 7. Here is a restatement:
# For each slip: if days_late > 7, fee = 2 * days_late. Otherwise fee = 0.
# Input: a list of slips. Output: total fee for all slips.
Two lines. Writing them exposes two questions right away. Is the fee charged on all the late days, or only on the ones past the seventh? The statement says every day, and the restatement says so too. And what does the function return: one total, or a fee per borrower? The statement says a report, which is vague, so the restatement picks one reading and names it. If the real task wanted a per-borrower breakdown, you have just found that out for the price of one comment, not a rewrite.
The constraints are part of the statement too, and they tell you how hard the problem is before you start. A line such as "n is between 1 and 10,000" says two things. The input is never empty, so you may not need a guard for that case, though adding one costs nothing. And 10,000 is small: a loop that visits each number once finishes at once, and even a loop over every pair of numbers, about 50 million steps, takes a few seconds in Python, which is fine for practice and too slow when a judge allows one second. When a constraint says 100,000 or a million instead, a loop inside a loop becomes too slow, and the later chapters of this track are about what to do then. Read the constraint, do the rough multiplication, and you know whether the direct approach is enough. For almost every problem in this chapter and the next two, it is.
Restating also catches the words that carry hidden weight. "In order" means the output must keep the input's sequence. "Distinct" means duplicates collapse. "Return" means hand the value back, not print it. "Consecutive" means neighbours only. Each of these has cost someone a wrong answer. Write them into the restatement so they cannot slip past you.
Examples first, then edge cases
Before writing code, write the answer for a small input by hand. Not in your head. On paper or in a comment, with the real values.
# slips: [("B10422", "asha", 3), ("B10091", "ravi", 9), ("B10310", "asha", 0)]
# asha, 3 days: not over 7, fee 0
# ravi, 9 days: over 7, fee 2 * 9 = 18
# asha, 0 days: fee 0
# expected total: 18
Working one example by hand does three things. It proves you understood the rule, because you had to apply it. It gives you a test with a known answer before the code exists. And it shows you the shape of the loop: one pass over the slips, a running total, a condition inside.
Now the edge cases. An edge case is an input that sits at a boundary of the rule or at the edge of what the data can be. For the fee report, list them:
- No slips at all. The total should be 0, and the code must not crash on an empty list.
- Exactly 7 days late. The rule says more than 7, so the fee is 0. This is the boundary, and it is the one you will get wrong if you type
>=by reflex. - Exactly 8 days late. Fee 16.
- A very large number of days, like 400. Still a fee, 800. Nothing special, but it checks that nothing is capped by accident.
- Days late is 0. Fee 0. Also on time, never negative.
You do not need twenty edge cases. You need the ones the rule's boundaries produce. Find each comparison in your restatement and ask what happens at the value itself, one below and one above. Find each collection and ask what happens when it is empty, when it has one element, and when everything in it is the same.
Here is the function, with the boundary tested:
def total_fee(slips):
total = 0
for accession, borrower, days_late in slips:
if days_late > 7:
total += 2 * days_late
return total
print(total_fee([])) # 0
print(total_fee([("B10422", "asha", 7)])) # 0, exactly 7 is not over 7
print(total_fee([("B10422", "asha", 8)])) # 16
print(total_fee([("B10422", "asha", 3), ("B10091", "ravi", 9), ("B10310", "asha", 0)])) # 18
Run that and you get 0, 0, 16 and 18. The hand-worked example matches. If the 7-day line had printed 14 instead of 0, you would have caught a >= the moment it happened, with the rule still fresh in your mind.
FizzBuzz, start to finish
Now the same habit on a problem you will meet in the exercise at the end of this chapter. It is short enough to show every step, and that is the point: the steps matter more than the problem.
The statement: return a list with one entry for every integer from 1 to n, in order. Each entry is a string. Write "Fizz" when the number divides evenly by 3, "Buzz" when it divides evenly by 5, "FizzBuzz" when it divides evenly by both, and the number written as text in every other case. The constraint is that n is between 1 and 10,000.
Step 1, restate it.
# For i from 1 to n (both ends included), in order:
# both 3 and 5 divide i -> "FizzBuzz"
# only 3 divides i -> "Fizz"
# only 5 divides i -> "Buzz"
# otherwise -> str(i)
# Return a list of strings. Every entry is a string, even the numbers.
Two things fell out of the restatement. The range includes both ends, so the loop is range(1, n + 1), not range(n). And every entry is a string, so the number case is str(i), not i. A list that mixes "Fizz" with the integer 4 fails the problem even though it looks right when printed.
Step 2, one example by hand. The statement gives n = 5. Work it: 1 is plain, 2 is plain, 3 divides by 3, 4 is plain, 5 divides by 5. Expected: ["1", "2", "Fizz", "4", "Buzz"]. The statement also gives n = 15 as its second example, the smallest case where both 3 and 5 divide a number, and position 15 must be "FizzBuzz". Work that one too, and then look for a case the statement did not give, because the given ones are the ones you are least likely to get wrong; the edge cases in the next step are those.
Step 3, edge cases. n = 1 returns ["1"], a list with one entry, not a bare string. n = 3 ends in "Fizz". The order of the checks matters: if you test "divides by 3" before "divides by both", 15 becomes "Fizz" and never reaches "FizzBuzz". So the both-case goes first.
Step 4, the plan, in words. Make an empty list. Loop from 1 to n. For each number, decide which of four strings to add, testing the both-case first. Return the list.
Step 5, code.
def fizz_buzz(n):
result = []
for i in range(1, n + 1):
if i % 3 == 0 and i % 5 == 0:
result.append("FizzBuzz")
elif i % 3 == 0:
result.append("Fizz")
elif i % 5 == 0:
result.append("Buzz")
else:
result.append(str(i))
return result
% gives the remainder after division, so i % 3 == 0 is "3 divides i with nothing left over". The elif chain runs top to bottom and stops at the first true test, which is why the both-case has to sit at the top.
Step 6, test against the examples you wrote.
print(fizz_buzz(1)) # ['1']
print(fizz_buzz(5)) # ['1', '2', 'Fizz', '4', 'Buzz']
print(fizz_buzz(15)[-1]) # FizzBuzz
print(len(fizz_buzz(15))) # 15
Four lines, and they check the four things the restatement and the edge cases named: one entry for n = 1, the given example, the both-case at 15, and the count. If the last line printed 14, you would know the range was wrong before reading a single line of the function again.
A detail worth seeing once: i % 15 == 0 is the same test as i % 3 == 0 and i % 5 == 0, because 3 and 5 share no factors. Both forms are fine. Write the one you can explain. If someone asks why 15, you should be able to say "because the first number both 3 and 5 divide is 15", not "because the solution I saw used it".
Here is the same function with the output built differently, so you see that the plan is what matters and the syntax is a choice:
def fizz_buzz_2(n):
out = []
for i in range(1, n + 1):
word = ""
if i % 3 == 0:
word += "Fizz"
if i % 5 == 0:
word += "Buzz"
out.append(word or str(i))
return out
print(fizz_buzz_2(15) == fizz_buzz(15)) # True
This version builds the word from parts. The two if tests are separate, not an elif chain, so 15 collects both halves. word or str(i) returns word when it is not empty and str(i) when it is, because an empty string counts as false. Some people find this clearer. Some find the first version clearer. Both pass every test, and the comparison line proves they agree for every number up to 15.
A habit you can repeat
Here is the whole routine as a checklist. Keep it next to you until it is automatic.
- Read the statement twice. The second time, restate it in your own words at the top of the file. Name the input and the output.
- Circle the loaded words. In order, distinct, return, consecutive, at most, at least, more than. Each one changes the code.
- Work one example by hand, including one the statement did not give you.
- List the edge cases from the boundaries: empty, one element, all the same, the exact value in every comparison, one above and one below.
- Write the plan in words, three or four lines. If you cannot write the plan, you are not ready to write the code, and typing will not fix that.
- Code the plan. Keep the names honest:
total,days_late,result, notxandtmp. - Run your examples, the hand-worked one and the edge cases, and compare with the answers you wrote down before coding.
Notice what is not on the list. There is no step called "think of the cleverest approach". For the problems in this track, the direct approach is usually right, and the chapters that follow teach you the handful of cases where it is too slow and what to do instead. Clever comes later and only when the direct way is measurably too slow.
One more thing about time. The checklist feels slow the first few times. It is not. The slow part of solving a problem is debugging code that was written for the wrong problem, and the checklist removes most of that. After ten or twenty problems the restatement takes thirty seconds and the examples take a minute, and you will notice that your first version passes more often than it used to.
The exercise for this chapter is FizzBuzz itself. Do it with the checklist even though you have just read the answer. Restate it, write n = 15 by hand, list the edge cases, and only then type. The next chapter picks up desk.py and gives it its first real data structures: the lists, tuples, sets and dictionaries that every later chapter is built on.