The fastest way to a new algorithm is usually one you already wrote. Combine procedures into something new, refine one to do the same job in fewer steps, and learn the only safe way to answer “do these two do the same thing?”
No reading — this page is the reading. Runestone doesn’t cover Unit 4 (search, efficiency, limits, simulation), so everything you need is right here.
Still building the Algorithms region of Programs. 4.1 said an algorithm is sequencing, selection, and iteration. Today: the fastest way to get a new algorithm is usually not to write one — it’s to combine or modify ones you already have.
highest(), average(), and count_passing() — you built them
in Lab 3.15. Today you build a brand-new one, a full class report, without writing a single new
loop.
The CED names three ways new algorithms get made: from an idea, by combining existing algorithms, or by modifying existing ones. Programmers do the last two far more than the first.
def class_report(scores): top = highest(scores) avg = average(scores) passed = count_passing(scores) return [top, avg, passed]
PROCEDURE classReport(scores) { top ← highest(scores) avg ← average(scores) passed ← countPassing(scores) RETURN ([top, avg, passed]) }
No loops, no IFs — just calls. Each procedure already works, so the new one works too. That’s the payoff of the procedures you wrote in Unit 3.
Same output, fewer steps. Here’s an average that walks the list twice
— once to add, once to count — next to one that walks it once:
total ← 0 FOR EACH s IN scores { total ← total + s } count ← 0 FOR EACH s IN scores { count ← count + 1 } RETURN (total / count)
total ← 0 FOR EACH s IN scores { total ← total + s } /* no counting loop */ /* LENGTH already knows */ RETURN (total / LENGTH(scores))
On 30 scores, “before” visits 60 elements and “after” visits 30. Same answer. Half the work. You just refined an algorithm — and counted the steps to prove it.
Pick a pair. Predict whether the two procedures always give the same result — then let the page run both on a batch of test lists, including the awkward ones.
No new terms to memorize today — this is CED 3.9’s “combining and modifying existing algorithms,” using procedures you already own.
Five questions. Trace both sides before you answer any “same result?” question.
Composition is powerful because one working procedure can power dozens of
programs. It cuts the other way, too. If average() has a bug, every report that calls it
is wrong — and none of those reports look wrong. Real software is built this way: apps call
libraries that call other libraries, and a single flaw deep in the stack can reach millions of devices
at once.
Reusing code is the right habit. Testing the pieces you reuse — with the awkward inputs — is the other half of it.