Have a go at it. The editor and the docs panel are open, and your code is saved as you type. Running it needs a free account — you’ll come back to exactly what you wrote.
The Off-by-One Loop
count_above is meant to count how many values are above a threshold. It returns the wrong number, and it is out by exactly one in a way that depends on the data.
def count_above(values, threshold):
count = 0
for i in range(len(values) - 1):
if values[i] > threshold:
count += 1
return countWork through it on [5, 10] with a threshold of 1:
len(values) is 2, so range(len(values) - 1) is range(1), which is just 0.values[0]. The last item is never checked.Somebody wrote - 1 because they remembered that indices stop one below the length. But range already excludes its stop value, so range(len(values)) gives exactly the valid indices and the - 1 removes a real item.
The general lesson: when a loop is out by one, trace it by hand on a two-item input. Two items is small enough to do in your head and big enough to show the bug.
Your task:
Fix count_above so it checks every value.
Example Tests
The last value is counted too
Input: {"values":[5,10],"threshold":1}
Expected: 2
Values equal to the threshold do not count, only strictly above
Input: {"values":[1,2,3],"threshold":2}
Expected: 1
Nothing above the threshold gives 0
Input: {"values":[1,1,1],"threshold":5}
Expected: 0
def count_above(values, threshold):
"""
Count how many values are strictly greater than threshold.
This currently misses the last value. Fix it.
Args:
values: a list of numbers
threshold: the number to compare against
Returns:
How many values are above the threshold.
"""
count = 0
for i in range(len(values) - 1):
if values[i] > threshold:
count += 1
return countRun your code to see results
⌘↵ runs against the visible tests