Skip to content
Your progress

Checking your sign-in…

Who's learning?

Each profile keeps its own read lessons, badges, streak, and practice scores on this device.

Lesson 7 of 11

Write the sum yourself

Show on a big screen

8 min

Text size

This term did the arithmetic by hand. Now you write it as code.

Inputs 6 and 0. Weights 6 and 4. Sum starts at 0.
Step 1 of 4
  1. Inputs 6 and 0. Weights 6 and 4. Sum starts at 0.
  2. Position 0: sum becomes 0 + 6 × 6 = 36.
  3. Position 1: sum stays 36, since 0 × 4 adds nothing.
  4. decide(36, 40): 36 is under 40. Answer: wait.

The rule

The weighted sum and the comparison are two short functions. At or past it says call. The day the sum equals the threshold says call.

A function is a named piece of code. It takes values in and returns one answer. Here inputs and weights are lists of numbers. weightedSum(inputs, weights) starts sum at 0. Position 0 is the first item in a list. A while loop repeats lines while a check is true. Here it goes through the positions, 0 first. Each time, the function adds one input times its own weight. Then decide(sum, threshold) returns true for a sum at or past the threshold. It returns false when the sum is under it. True means call, false means wait.

The lab keeps two days hidden from view. One day's sum equals the threshold exactly. A check of "greater than" alone gives wait there. A check of "at or past" gives call. The other day is an empty day, with no inputs at all. Its sum must still be 0.

Both functions start wrong on purpose. They return a sum of 0 and the verdict wait. Change them until they work out the right answers.

Loading lab…

Try the lab to finish this lesson.