The problem
Each function below has a bug. For each one, find an input list that makes it give the wrong answer. This is a counterexample, as in lesson 4. Write counterexample(which) so that it returns your list for function number which.
# 1. Should return how many times the list goes up
# from one value to the next.
def count_rises(a):
count = 0
for i in range(1, len(a) - 1):
if a[i] > a[i - 1]:
count += 1
return count
# 2. Should return True if the list is in order.
def is_sorted(a):
return len(a) == 0 or a[0] <= a[-1]
# 3. Should return the index of the first place where
# the largest value appears (the list is not empty).
def first_max_index(a):
best = 0
for i in range(len(a)):
if a[i] >= a[best]:
best = i
return best
# 4. Should return the second largest different value
# (the list has at least two different values).
def second_best(a):
return sorted(a)[-2]
Your list must meet each function’s input condition. Use only whole numbers. For functions 2 and 3, the list must not be empty, and for function 4 it must hold at least two different values. The tests run the correct version beside the buggy one and check that the answers differ.
Limits
- Return a list (not a tuple) for each of the four.
Builds on CORR-4 Contradiction and counterexamples and CORR-5 Testing versus proving.
Continue on a laptop
Practice runs Python in the browser and needs a keyboard and a wider screen. Read the problem and open hints here, then write your solution on a laptop. Progress is saved per browser for now, so hints opened here stay on this device.
Need a hint?0 of 3 opened
- Hint 1Nudge
- Hint 2Approach Open hint 1 first
- Hint 3Pseudocode Open hint 2 first
- Worked solutionlast resort Opens after all 3 hints
Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.
| # | Test | Result | Reads · time |
|---|---|---|---|
| 1 | Break count_rises | Not run | |
| 2 | Break is_sorted | Not run | |
| 3 | Break first_max_index | Not run | |
| 4 | Break second_best | Not run | |
| 5 | Returns lists of whole numbers | Not run |