1. Simple debugging

VCMNA282: level 8: Use algorithms and related testing procedures to identify and correct errors
  • Debugging search and sort programs


1.1. Errors and debugging

An error in code is called a bug.
Correcting the errors in code is called debugging.
Debugging includes checking that the algorithm returns the correct output from a given input.
To help find errors in the code, test smaller sections of the code by printing the result part way to see if, at that point, it is correct.

1.2. Checking that a list has been sorted in ascending order

The list, [12, 13, 14, 16, 12, 17], is not sorted in ascending order.
The number 12 at index 4 is out of order.
The function below can be used to indicate that the list was not sorted correctly.
A second list, that is correctly sorted, is included as well.
 1def check_sorted_list(sorted_list):
 2    """This function takes in a list of numbers and checks if it is sorted in ascending order.
 3    
 4    Args:
 5        sorted_list (list): A list of numbers
 6    
 7    Returns:
 8        bool: True if the list is sorted, False otherwise
 9    """
10    is_list_sorted = True
11    for i in range (len(sorted_list)-1):
12        if sorted_list[i+1] < sorted_list[i]:
13            is_list_sorted = False
14    return is_list_sorted
15
16mylist = [12, 13, 14, 16, 12, 17]
17print(mylist, "sorted", check_sorted_list(mylist))
18# [12, 13, 14, 16, 12, 17] sorted False
19
20mylist = [12, 12, 13, 14, 16, 17]
21print(mylist, "sorted", check_sorted_list(mylist))
22# [12, 12, 13, 14, 16, 17] sorted True