AI Launch Lab
Sign in FR Get updates

AI foundations · Lesson 2 of 3

A first prediction

A prediction uses past examples to guess an unknown value. One of the simplest methods is the nearest neighbour: find the past example most similar to the new case, and reuse its answer.

Say a moving company records each job as (rooms, hours): [(1, 3), (3, 7), (5, 11)]. For a new 4-room job, the nearest examples are 3 and 5 rooms. If two are equally close, a rule must decide; here we keep the first one found.

This method has no formula to learn: the examples are the model. It works surprisingly well when there are many good examples, and badly when the new case looks like nothing seen before.

Your turn

Write nearest(examples, x): examples is a list of (x, y) pairs. Return the y of the example whose x is closest to the given x. On a tie, return the first one in the list.

Loading Python (about 12 MB, once)…

    Checks

    • ○ exact match returns its value
    • ○ closest example wins
    • ○ a tie keeps the first example
    • ○ works below the smallest example

    Output

    ← Previous lesson All courses