Problem Solving: Beginner
From sentence to steps
- Start a counter at 0, because no orders have been checked yet.
- Look at each order total, one at a time.
- If the total is more than 50, add 1 to the counter.
- After the last order, the counter holds the answer.
Each step names 1 thing Python can do: an assignment, a for loop, an if with an assignment inside it, and a return. The translation is 1 line per step, with the loop body indented under its step.
| Step | Code |
|---|---|
| 1. Start a counter at 0 | count = 0 |
| 2. Look at each order | for total in orders: |
| 3. More than 50? Add 1 | if total > 50: count = count + 1 |
| 4. Report the counter | return count |
Of the 4 totals, 2 come out: 65 and 120 are over 50, 20 is under, and 50 sits on the line. The problem said over 50, and over means strictly more, so the 50 dollar order pays shipping. That decision was made at step 3, in words, before the > was typed, which is where boundary decisions belong.
Steps that need more than 1 variable
- Start a running sum at 0 and a running count at 0.
- Look at each rating.
- If the rating is greater than 0, add it to the sum and add 1 to the count.
- After the loop, divide the sum by the count.
Step 3 became 2 lines under 1 if, because both totals change under the same condition. Step 4 is the one that would go wrong if a product had only zeros: the count would be 0 and the division would fail. Catching that is the job of the last section of this lesson; the step list is what made it catchable, because 'divide the sum by the count' is a sentence you can question.
Practice
A teammate asks: given a list of daily temperatures, how many days were at least 30 degrees? Which step list translates the question?
Each blank in the next program comes from a word in its step list. 'Start a counter at 0' sets the starting value. 'More than 10' sets both the operator and the number it compares against. 'Add 1' sets how much the counter grows on each match. Before you submit, check the 10 kilogram package against your comparison: > 10 leaves it out, and >= 10 would count it.
Write the pairs first
| Input | Output | Why |
|---|---|---|
| [] | [] | No days recorded, so no days met the goal. |
| [12000] | [12000] | One day, and it met the goal. |
| [8000, 12000, 10000] | [12000, 10000] | 10000 meets the goal because met means reached. |
| [9999, 500] | [] | Both fell short, so the answer is an empty list; the number 0 would be the wrong type. |
Input type, output type
| Input | Output | Function returns |
|---|---|---|
| list of prices [4.5, 12.0, 7.25] | 12.0 | a float, the price |
| list of (name, price) tuples | "headphones" | a string, the name |
| list of (name, price) tuples | ("headphones", 12.0) | a tuple, the whole item |
All 3 are reasonable, and only the caller knows which one they want. Writing the type hint on the signature forces that question before the body exists: -> float, -> str and -> tuple describe 3 different functions. The float version compares each item directly. The 2 tuple versions share 1 loop that compares item[1] and keeps the whole tuple. They differ only in the return line: best[0] for the name, best for the item.
Each item is a tuple, so item[1] is the price being compared and best[0] is the name being returned. The input row said tuples and the output row said string, and those 2 index positions follow from the rows.
- ▸Is the output 1 value or a collection?
- ▸Does the boundary value count?
- ▸What comes back when the input is empty?
- ▸What type is each thing, and does the type hint match it?
Practice
Problem: given a list of exam scores, return how many students scored under 40. A teammate writes these input and output pairs. Which pair is wrong?
A function that returns the values that passed a test has the same shape as goal_days, and its pairs table predicts its code. The result starts as [], because an input where nothing passes must return an empty list. The comparison carries the boundary the sentence names, and .append adds each kept value in input order. When no value passes, the function returns the [] it started with, unchanged. That is the empty row of the table.
Swapping 2 values in 3 lines
Start with 6 lines and no loop. Before pressing play, write down what you expect x and y to be at the end, then watch each line change the stage.
x = 5y = 3x = x + yy = x - yx = x - yprint("x =", x, "y =", y)
Each right side reads the values the previous line left behind.
| Line | x | y |
|---|---|---|
| x = 5 | 5 | |
| y = 3 | 5 | 3 |
| x = x + y | 8 | 3 |
| y = x - y | 8 | 5 |
| x = x - y | 3 | 5 |
The third line reads x on the right before it writes x on the left, so x + y is 5 + 3 and the new x is 8. The fourth line then uses that 8, and 8 minus 3 is 5. The trace shows the swap works because each right side reads the values the previous row left behind. Someone who skims the code and sees 'add then subtract' usually predicts the values end unchanged.
Tracing a loop
A loop adds 1 row per pass. This program peels the digits off a number from the right: num % 10 is the last digit and num // 10 drops it. Trace it with 3 columns before running it.
num = 123total = 0while num > 0:digit = num % 10total = total + digitnum = num // 10print("Sum of digits:", total)
The loop makes 3 passes, then a fourth check finds num equal to 0 and stops.
| Pass | digit | total | num after |
|---|---|---|---|
| before loop | 0 | 123 | |
| 1 | 3 | 3 | 12 |
| 2 | 2 | 5 | 1 |
| 3 | 1 | 6 | 0 |
| check | 6 | 0, so the loop stops |
The loop condition is checked before every pass, and a fourth check finds num equal to 0 and stops the loop. The table has 1 numbered row per pass. Counting the numbered rows, and leaving out 'before loop' and 'check', answers 'how many times did the body run': 3.
Every trace of a while loop ends with 1 more condition check than it has passes. If you skip the check after pass 3, you run the body again with num equal to 0 and write a fourth row that never happened. The check row is what tells you to stop.
Tracing a loop over a list
With a for loop over a list, the loop variable takes each item in order, and the trace needs a column for it. This program keeps the highest score seen so far. Write the trace table yourself before playing it, then compare.
scores = [42, 17, 58, 23]best = scores[0]for score in scores:if score > best:best = scoreprint("Highest:", best)
Only the 58 pass changes best.
| score | score > best? | best |
|---|---|---|
| start | 42 | |
| 42 | no | 42 |
| 17 | no | 42 |
| 58 | yes | 58 |
| 23 | no | 58 |
The first pass compares 42 to itself and does nothing, which is correct and harmless. The only row that changes best is the 58 row. A trace table like this is the fastest way to answer a question such as 'what if the list were [3, 9, 9]': 2 rows say no, 1 row says yes, and best ends at 9.
Practice
Trace this program by hand. What does it print?
When a trace ends on the wrong number, the first row where it goes wrong points at the line to fix. Add a column for the condition itself and write yes or no beside each item. If the total grows on rows that should say no, the test is backwards. If it grows by the wrong amount on the yes rows, the body is wrong. For an even number n % 2 is 0, and for an odd number it is 1.
| The question starts with | Pattern | Skeleton |
|---|---|---|
| What is the total ... | Accumulate | total = 0, add each item |
| How many ... | Count | count = 0, add 1 when the condition holds |
| What is the largest / smallest ... | Best so far | best = items[0], replace when an item beats it |
| Which items ... | Filter | kept = [], append when the condition holds |
| How many of each ... | Tally | counts = {}, add 1 under the item's key |
| Is there any / find the first ... | Search | loop, and break at the first match |
Accumulate, count, filter
These 3 share a loop and differ in what sits before it and what the body does. The starting value is the answer for an empty list: 0 for a total, 0 for a count, [] for a filter.
Best so far
Tally
A question with 'of each' in it wants a dictionary: the items are keys and the counts are values. The body has to handle a key seen for the first time, because reading a missing key fails, so the pattern checks in before adding.
Search
A search stops at the first match, and break is what stops it. The result variable starts as a value that means 'not found', so a list with no match still leaves something to return.
- 'total of' means accumulate
- 'how many' means count
- 'which ones' means filter
- 'of each' means tally
- the exact comparison and its boundary
- the start value for an empty input
- the type of each item being read
- the value that means 'not found'
Practice
A product manager asks: of all the support tickets opened this week, how many came in from each region? Which pattern fits?
Changing 1 character turns cheapest into a function that finds the longest or largest value: price < best becomes price > best. The start value is still the first item, and the assignment inside the if still writes the item into best. With the direction pointing the wrong way, the loop still runs without an error and returns the smallest value. Only a known answer catches that.
A function that looks right
| Input | Expected | Why |
|---|---|---|
| [4] | 4 | One value, so it is the largest. |
| [3, 9, 2] | 9 | Ordinary case. |
| [-3, -7] | -3 | Both negative; -3 is closer to zero. |
| [] | no answer yet | Nothing to be largest; the function needs a decision. |
Of the 3 rows, 2 agree and the third does not. With best starting at 0, no negative value ever beats it, so the function returns a 0 that was never in the list. The fix is the start value from the best so far pattern: best = values[0]. The empty list row is the other finding. values[0] fails on an empty list, so the function must decide what empty means. Here the caller agreed that an empty list returns 0. A temperature change of 0 is a real value, though, so a result of 0 can no longer say whether the list was empty. Choosing a different value to mean 'nothing' is a decision for a later lesson.
The same style of printing now agrees on every row. The [5, 5, 5] case was added because a list of equal values is where a comparison written as >= instead of > shows a difference in which item wins. Here neither choice changes the printed answer.
Choosing the small cases
- ▸Empty input: does the function return something sensible or fail?
- ▸One item: the loop runs once, so the start value can't hide.
- ▸2 items, in each order: catches a comparison pointing the wrong way.
- ▸The boundary value itself: 50 for 'over 50', 10000 for 'at least 10000'.
- ▸Negatives and zeros: start values of 0 are exposed.
- ▸All equal: ties show whether the first or the last item wins.
Expected first, run second
The order matters. Writing the expected answer before running the code means the code can't talk you into its answer. Running first and then nodding at the output is how a 0 for [-3, -7] gets accepted, because 0 looks like a plausible number until you remember that it was never in the list.
- Write the expected answer next to each input before running.
- Start with the empty list and 1 item.
- Put the boundary value in a test on its own.
- Test only with the example from the problem statement.
- Run first and decide afterwards whether the output looks right.
- Skip negatives because the real data is 'always positive'.
Practice
Which small input finds the problem in this function?
Capstone: one problem, all 5 habits
> A payments team at Stripe is asked for a report: for each merchant, how many of their refunds this month were over 500 dollars, and what was the largest single refund?
Turn a sentence into steps, trace them by hand, and test them small before any real data arrives.
- Category
- Python
- Difficulty
- beginner
- Duration
- 20 minutes
- Challenges
- 19 hands-on challenges
Topics covered: Breaking Problems into Steps, Input/Output Analysis, Tracing Code Manually, Pattern Recognition, Testing Simple Cases
Lesson Sections
- Breaking Problems into Steps (concepts: Functions)
A word problem arrives as a sentence, and Python runs lines. The work between them is a list of steps in plain words, each small enough that you already know the line of code it becomes. Writing that list first means the code is a translation, and a translation is checked line by line against its source. From sentence to steps Here is a problem as a teammate would phrase it: a store gives free shipping on orders over 50 dollars, and we have the list of order totals from today, so how many orders
- Input/Output Analysis (concepts: Functions)
Before a function has a body, it has a shape: what comes in, what goes out, and what type each is. Writing 3 or 4 input and output pairs by hand pins that shape down. Each pair is a small fact about the problem that the finished code will be held to, and the pairs usually expose the questions the sentence left open. Write the pairs first Problem: a fitness app records daily step counts, and we want the days that met the 10000 step goal. Before deciding anything about loops, fill a table of input
- Tracing Code Manually (concepts: Conditional Loops)
Tracing is running the program yourself: a table with a column per variable, and a new row each time a line changes one. It's slow, which is the reason it works. Reading code lets you believe what it does; tracing it shows what it does, and the 2 differ more often than anyone expects. Swapping 2 values in 3 lines Tracing a loop Every trace of a while loop ends with 1 more condition check than it has passes. If you skip the check after pass 3, you run the body again with num equal to 0 and write
- Pattern Recognition (concepts: Iteration)
After a few dozen problems, the loops stop being new. Most of them are 1 of 6 shapes, and the sentence that describes a problem usually names its shape in the first few words. Recognizing the shape means the loop's skeleton is written before you think, and the thinking goes into the condition and the values, where it belongs. Accumulate, count, filter Best so far Finding a largest or smallest value keeps 1 current best and tests it against every item. The current best starts as the first item, w
- Testing Simple Cases (concepts: Testing)
A function that has been written hasn't been checked. The check is running it on inputs small enough that you know the answer without the function: an empty list, 1 item, 2 items, values at the boundary, values that are all the same. Each such run costs a few seconds, and each one that disagrees with your known answer is a bug found before a real dataset hides it among 10 million rows. A function that looks right This function is meant to return the largest value in a list of temperature changes