Editor

Closest to the Target

#535 · Lists · Beginner · 30 XP · about 5 min

At a school fair, everyone guesses how many jelly beans are in a jar. Write closest_guess(guesses, target) that returns the guess nearest to target, the real number of beans.

The distance between a guess and the target is abs(guess - target). If two guesses are equally close, return the one that comes first in the list. The list always has at least one guess.

Examples

closest_guess([120, 98, 150], 100)  # returns 98
closest_guess([90, 110], 100)       # returns 90
closest_guess([500], 3)             # returns 500

In the second example both guesses are 10 away, so the first one, 90, wins.

Fastest solvers

Leaderboard

First solves only, ranked by stars and then time.