CORR-P4

Break these functions

Practice 4 of 5Correctness5 tests

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

  1. Hint 1Nudge
  2. Hint 2Approach Open hint 1 first
  3. Hint 3Pseudocode Open hint 2 first
  4. Worked solutionlast resort Opens after all 3 hints
Python waits for a wider screensolution.py

Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.

5 tests, not run yet
Test results
#TestResultReads · time
1Break count_risesNot run
2Break is_sortedNot run
3Break first_max_indexNot run
4Break second_bestNot run
5Returns lists of whole numbersNot run