ICS3U Computer Science • Ontario Grade 11

Corrected exercises: array algorithms (ICS3U)

Exercises: array algorithms (ICS3U)

Name: Class: Date:

Solutions

Suggested time: 2 h 30 · No calculator · 10 exercises
https://www.letuteurscientifique.ca/en/exercices/ics3u-array-algorithms

These ten corrected exercises cover the sixth chapter of ICS3U, Introduction to Computer Science, Grade 11, University Preparation, in Ontario: algorithms with nested structures on a one-dimensional array, counting elements, calculating a total and an average, finding the highest or lowest value, performing a linear search, and designing simple algorithms to add data to a sorted array and delete a datum from the middle of an array.

What the set covers, the traps it targets

The code is in Python 3, where an array is a list; each algorithm is written with a loop, without max(), sum(), in, index(), insert() or pop(), and is traced the same way in any language.

By the end, you can count and total in one traversal and guard an average (exercise 1), find the largest value and its index and choose between > and >= on a tie (exercise 2), give the position found by a linear search, or -1, and count its comparisons for one run (exercise 3), insert into a sorted array by shifting from the right (exercise 4), and delete from the middle by shifting to the left (exercise 5). Part B corrects three faulty searches (exercise 6), repairs the report of a losing soccer season (exercise 7), corrects five statements (exercise 8), keeps the high-score table of an arcade game in order (exercise 9), and removes a student from the waitlist of a ski trip (exercise 10).

The thread of the set: an array algorithm is one traversal plus a few variables that remember what it has seen. They start from a value that is right before the first pass, the conclusion comes after the loop, and a shift always copies into a cell whose value has already moved. Five traps are named in the solutions: (1) a maximum started at 0, which fails on an array of negative values, exercises 2, 7 and 8; (2) a linear search that concludes « not found » inside the loop, from a single element, exercise 6; (3) an insertion that shifts from the left and overwrites every later cell, exercises 4, 8 and 9; (4) a deletion that does not reduce size and leaves the last value twice, exercises 5 and 10; (5) the average of an empty array, which divides by zero, exercises 1, 7 and 8. A tie read with > or >= (exercises 2 and 9), a search that stops one cell early (exercise 6), a deletion that shifts in the wrong direction (exercise 5) and the position -1 used as an index (exercise 10) come back as well.

No calculator is needed: every count, every shift and every output is worked out by hand, as on a unit test. Sorting an array, binary search and subprograms that insert and delete belong to the Grade 12 course, ICS4U; here the algorithm is designed and traced in a main program.

  • 10 corrected exercises • 100 points • 150 minutes
  • Self-checking, 108 answers
  • No calculator
Start exercise 1 The chapter sheet
Print

Print the homework or the solutions

The homework without solutions, one exercise per page, and the solutions on their own: it comes with your free space. An email is enough, no password, and you come back here.

Create my free space

Already have one? Sign in

Course recap

  • • Count and total: a variable set to 0 before the loop, changed by each pass, read after the loop.
  • • Average: total / len(a), only if len(a) > 0.
  • • Largest or smallest value: start from a[0], compare a[1] to a[len(a) - 1]; > keeps the first occurrence of a tie, >= the last.
  • • Linear search: pos = -1, then compare each element in turn until pos changes or the array ends; -1 means not found.
  • • « Not found » is concluded after the loop, never in the else of the test.
  • • Partially filled array: size counts the cells in use, from index 0 to size - 1.
  • • Insertion into a sorted array: shift from size - 1 down while the cell is greater, write into the gap, then size + 1.
  • • Deletion at pos: shift from pos up to size - 2, a[i] = a[i + 1], then size - 1.

Part A: the basics (/50)

Exercise 1: Counting and totalling: one traversal, two accumulators

10 answers to check

The program below traverses an array once. Each pass adds the current element to total and, when the element is at least 10, adds 1 to count. Trace it with one row per pass, then answer.

Python
a = [14, 9, 23, 6, 18, 8, 13]    # line 1
count = 0                        # line 2
total = 0                        # line 3
for i in range(len(a)):          # line 4
    total = total + a[i]         # line 5
    if a[i] >= 10:               # line 6
        count = count + 1        # line 7
print(count, total)              # line 8
  • a) What do total and count hold after the third pass, i = 2?
  • b) What does line 8 print?
  • c) A line 9 must print the average of the seven values. Which line is right? What does it print?
  • d) Line 1 becomes a = [], an array with no element. What does line 8 print? What does the line 9 chosen in c) do?
  • e) Write the lines, placed after line 9, that count the values strictly greater than the average. What is that count for the array of line 1?

Type your answers, the page tells you right or wrong 0/10

a)
b)
c)
d)
e)
Show the solution

Answers

  • a) total = 46 and count = 2
  • b) 4 91
  • c) print(total / len(a)), which prints 13.0
  • d) 0 0, then line 9 stops the program with a ZeroDivisionError
  • e) 3 values (14, 23 and 18)

A count and a total follow one pattern: a variable set before the loop, changed by each pass, read after the loop. The trace table below follows lines 4 to 7; the program above is the complete answer, with the guard of part d) and the count of part e).

a)

Pass 1, i = 0: total = 0 + 14 = 14, and 14 >= 10 is True, so count = 1.

Pass 2, i = 1: total = 14 + 9 = 23; 9 >= 10 is False, count stays 1.

Pass 3, i = 2: total = 23 + 23 = 46; 23 >= 10 is True, count = 2.

After the third pass, total = 46 and count = 2.

b)

The last four passes add 6, 18, 8 and 13: total = 46 + 45 = 91.

Of these four values, 18 and 13 pass the test, so count = 2 + 2 = 4.

Line 8 prints 4 91. The value 13 is counted: >= includes the bound 10 itself, and so would 10 be.

Check: sum(a) also gives 91. The expected answer is the loop, which is what a unit test asks you to write.

c)

The average is the total divided by the number of values: print(total / len(a)) prints 91 / 7 = 13.0. In Python, / always gives a float, hence 13.0 and not 13.

Pitfall: total / count divides the total of all seven values by the number of values at least 10: 91 / 4 = 22.75 is neither the average of the array nor the average of its four large values, (14 + 23 + 18 + 13) / 4 = 17.0.

d)

With a = [], range(len(a)) is range(0): the loop makes no pass, count and total keep their starting values, and line 8 prints 0 0.

Line 9 then computes 0 / 0, and Python stops the program with ZeroDivisionError: division by zero.

Pitfall: an empty array has no average. The guard goes before the division: if len(a) > 0:, with a message such as No values otherwise.

e)

The average must be known before the test, so the count is a second traversal, after the first one.

average = 91 / 7 = 13.0; the values strictly greater are 14, 23 and 18: 3 values.

13 equals the average and is not counted. With >= the count would be 4, so the comparison follows the words of the question: strictly greater means >.

Python
a = [14, 9, 23, 6, 18, 8, 13]
count = 0
total = 0
for i in range(len(a)):
    total = total + a[i]
    if a[i] >= 10:
        count = count + 1
print(count, total)
if len(a) > 0:
    average = total / len(a)
    print(average)
    above = 0
    for i in range(len(a)):
        if a[i] > average:
            above = above + 1
    print(above)
else:
    print('No values')
Passia[i]a[i] >= 10?totalcount1014yes141219no2313223yes462436no5225418yes703658no7837613yes914One row per pass: total after line 5, count after line 7

Tick the exercises you have done or want to review: a free account, no password, keeps your ticks and your right answers from one visit to the next, tells you which chapter to tackle next and lets you ask for the exercise you are missing. Create your space, an email is enough.

Exercise 2: The largest value and its index: start from a[0], compare each element once

14 answers to check

The program below finds the largest value of an array and the index where it was found. largest holds the best value seen so far and where its index.

Python
a = [31, 47, 12, 47, 5, 29]    # line 1
largest = a[0]                 # line 2
where = 0                      # line 3
for i in range(1, len(a)):     # line 4
    if a[i] > largest:         # line 5
        largest = a[i]         # line 6
        where = i              # line 7
print(largest, where)          # line 8
  • a) How many times does line 6 run? What does largest hold after the pass i = 3?
  • b) What does line 8 print?
  • c) Line 5 becomes if a[i] >= largest:. What does line 8 print now? How many times does line 6 run?
  • d) The program is changed to find the smallest value: smallest = a[0] on line 2, if a[i] < smallest: on line 5, smallest = a[i] on line 6. What does line 8 print? How many comparisons does line 5 make on this array?
  • e) With the original program, line 1 becomes a = [8]: what does line 8 print? With a = [], what happens? A student suggests largest = 0 on line 2, so that the program never reads a[0]: what would line 8 print as largest for a = [-7, -3]?

Type your answers, the page tells you right or wrong 0/14

a)
b)
c)
d)
e)
Show the solution

Answers

  • a) Line 6 runs once; largest = 47 after the pass i = 3
  • b) 47 1
  • c) 47 3; line 6 runs 2 times
  • d) 5 4; 5 comparisons
  • e) 8 0 for [8]; an IndexError on line 2 for []; 0 for [-7, -3], a value that is not in the array

largest starts with a real element of the array, so it is the right answer before the first pass, for an array of one element. The loop can then start at index 1. The table below follows the six elements.

a)

i = 1: 47 > 31, line 6 runs, largest = 47 and where = 1.

i = 2: 12 > 47 is False. i = 3: 47 > 47 is False, a tie is not strictly greater. i = 4: 5 > 47 False. i = 5: 29 > 47 False.

Line 6 runs once, and largest is 47 from the pass i = 1 on, so also after the pass i = 3.

b)

Line 8 prints 47 1: the value, then the index of its first occurrence.

Check: max(a) also gives 47, but not the index where it was found.

c)

With >=, the tie at i = 3 passes the test: line 6 runs at i = 1 and at i = 3, 2 times, and where becomes 3.

Line 8 prints 47 3: the same value, but the index of the last occurrence.

Pitfall: > against >= changes nothing for largest and everything for where. The question decides: first occurrence, >; last occurrence, >=.

d)

smallest starts at 31. i = 1: 47 < 31 False; i = 2: 12 < 31, smallest = 12, where = 2; i = 3: 47 < 12 False; i = 4: 5 < 12, smallest = 5, where = 4; i = 5: 29 < 5 False.

Line 8 prints 5 4.

Line 5 runs once per pass, for i = 1 to 5: 5 comparisons, len(a) - 1. Check: min(a) gives 5.

e)

a = [8]: range(1, 1) is empty, the loop makes no pass, and line 8 prints 8 0. The start a[0] is already the answer.

a = []: line 2 reads a[0], and an empty array has no cell 0: the program stops with an IndexError on line 2. An empty array has no largest value; a program that may receive one tests len(a) > 0 first.

largest = 0 with a = [-7, -3]: -7 > 0 and -3 > 0 are both False, so largest stays 0 and line 8 prints 0 0.

Pitfall: a maximum started at 0 answers 0 for an array of negative values, a value that is not in the array. Start from a[0].

Passia[i]line 5largestwherebefore310114747 > 31: yes471221212 > 47: no471334747 > 47: no4714455 > 47: no471552929 > 47: no471Lines 5 to 7, one row per pass; in red, the tie that > does not take

Exercise 3: Linear search: the position or -1, and the comparisons of one run

10 answers to check

A linear search compares the target with each element in turn, from index 0, and stops as soon as it finds it. pos holds -1 while the target has not been found: -1 is not an index of codes, so it cannot be mistaken for a position. In this exercise, a comparison is one test codes[i] == target on line 6; the tests of line 5 are not counted.

Python
codes = [305, 118, 742, 118, 560, 233, 891]    # line 1
target = int(input('Code: '))                  # line 2
pos = -1                                       # line 3
i = 0                                          # line 4
while i < len(codes) and pos == -1:            # line 5
    if codes[i] == target:                     # line 6
        pos = i                                # line 7
    i = i + 1                                  # line 8
print(pos)                                     # line 9
  • a) The user types 742. What does line 9 print? How many comparisons are made?
  • b) The user types 118. What does line 9 print? How many comparisons are made?
  • c) The user types 400. What does line 9 print? How many comparisons are made?
  • d) The test and pos == -1 is removed from line 5. The user types 118. What does line 9 print now? How many comparisons are made?
  • e) With the program of lines 1 to 9, which code typed by the user makes exactly 4 comparisons? How many comparisons does the code 891 make?

Type your answers, the page tells you right or wrong 0/10

a)
b)
c)
d)
e)
Show the solution

Answers

  • a) 2, after 3 comparisons
  • b) 1, after 2 comparisons
  • c) -1, after 7 comparisons
  • d) 3, after 7 comparisons
  • e) No code makes exactly 4 comparisons; 891 makes 7

Count the comparisons on a drawing of the cells: the search reads codes[0], codes[1] and so on until pos changes or i reaches len(codes) = 7. The drawing shows the run of part b).

a)

i = 0: 305 == 742 False; i = 1: 118 == 742 False; i = 2: 742 == 742 True, pos = 2.

Line 5 then sees pos == -1 False and the loop stops: line 9 prints 2, after 3 comparisons.

A target found at index k costs k + 1 comparisons in this program.

b)

i = 0: 305 == 118 False; i = 1: 118 == 118 True, pos = 1, and the loop stops.

Line 9 prints 1, after 2 comparisons. The second 118, at index 3, is never reached: this search gives the first occurrence.

c)

400 matches no element: pos stays -1 and the loop ends when i reaches 7.

Line 9 prints -1, after 7 comparisons, one per element.

-1 is the agreed answer for « absent »: the program that uses pos must test pos == -1 before using it as an index.

d)

Without the test on pos, the loop always makes 7 passes. pos receives 1 at i = 1, then 3 at i = 3, and nothing changes it after that.

Line 9 prints 3, after 7 comparisons: the search now gives the last occurrence, and it never stops early.

Pitfall: the stop condition is half of the search. Without it, the result is still a position of 118, but the last one, and every run costs 7 comparisons.

e)

Exactly 4 comparisons would mean a target found first at index 3. codes[3] = 118, but 118 is found first at index 1, after 2 comparisons. 560 is found at index 4, after 5, and 233 at index 5, after 6. No code makes exactly 4 comparisons.

891 is the last element: 7 comparisons, the same number as an absent code. The two runs differ in their result, 6 against -1, not in their cost.

Counting the comparisons of one run is a trace. Comparing searches in general, best and worst cases, linear against binary search, belongs to the Grade 12 course, ICS4U.

305118742118560233891index01234561st2ndtarget = 118: two comparisons, pos = 1, the loop stopsgrey: no match; green: found; the 118 at index 3 is never compared

Exercise 4: Inserting into a sorted array: shifting from the right

12 answers to check

A Java array has a fixed number of cells. ICS3U programs therefore often keep spare cells at the end and a variable size that counts the cells in use: indices 0 to size - 1 hold the data, in increasing order here, and the others are free. The Python programs of this set work the same way: the list keeps its length, and size does the counting. To insert a value, the program makes room by moving cells one step to the right, starting from the last cell in use.

index0123456a121925314000size = 5: cells 0 to 4 in use, cells 5 and 6 spare (grey)
Python
a = [12, 19, 25, 31, 40, 0, 0]    # line 1
size = 5                          # line 2
value = 22                        # line 3
i = size - 1                      # line 4
while i >= 0 and a[i] > value:    # line 5
    a[i + 1] = a[i]               # line 6
    i = i - 1                     # line 7
a[i + 1] = value                  # line 8
size = size + 1                   # line 9
print(a, size)                    # line 10
  • a) How many times does line 6 run? What does i hold when the loop stops?
  • b) At which index does line 8 write 22? Why does that cell no longer hold data that must be kept?
  • c) What does line 10 print? Give a[3], a[5] and size.
  • d) A student shifts from the left instead. Knowing that 22 goes at index 2, he replaces lines 4 to 8 by for j in range(2, size): a[j + 1] = a[j], then a[2] = value. What does a[5] hold at the end? How many of the five original values are lost?
  • e) From line 1 again, value = 50: how many times does line 6 run, and at which index does 50 go? Same questions for value = 5.

Type your answers, the page tells you right or wrong 0/12

a)
b)
c)
d)
e)
Show the solution

Answers

  • a) 3 times; i = 1
  • b) Index 2: its value, 25, was copied into a[3] by the last shift
  • c) [12, 19, 22, 25, 31, 40, 0] 6: a[3] = 25, a[5] = 40, size = 6
  • d) a[5] = 25; 2 values lost, 31 and 40
  • e) 50: 0 shifts, index 5; 5: 5 shifts, index 0

Each pass copies a cell into its right neighbour, and that neighbour has already been saved: the first copy goes into the spare cell a[5], each later one into the cell copied just before. The drawing shows the array after each shift.

a)

i = 4: 40 > 22, a[5] = 40, i = 3.

i = 3: 31 > 22, a[4] = 31, i = 2.

i = 2: 25 > 22, a[3] = 25, i = 1.

i = 1: 19 > 22 is False, the loop stops. Line 6 ran 3 times, once per value greater than 22, and i = 1.

b)

Line 8 writes a[i + 1] = a[2] = 22. The loop stops at the first value not greater than 22, here 19 at index 1, so 22 goes just after it.

a[2] still shows 25, but that 25 was copied into a[3] by the last shift: a[2] is the gap the shifts opened.

c)

Line 10 prints [12, 19, 22, 25, 31, 40, 0] 6.

a[3] = 25, a[5] = 40, size = 6: one spare cell, a[6], is left. The array is still in increasing order.

d)

j = 2: a[3] = a[2] = 25, and 31 is overwritten. j = 3: a[4] = a[3], which is now 25, and 40 is overwritten. j = 4: a[5] = a[4] = 25. Then a[2] = 22.

The array is [12, 19, 22, 25, 25, 25, 0]: a[5] = 25, and 31 and 40 are lost, 2 values.

Pitfall: shifting from the left copies each cell into a neighbour that has not been saved yet, so the same value spreads to the end. Shift from the right, from size - 1 down to the insertion index.

e)

value = 50: at i = 4, 40 > 50 is False at once. Line 6 runs 0 times and 50 goes at index i + 1 = 5, after 40.

value = 5: every value is greater than 5, so line 6 runs 5 times, i goes down to -1, and the test i >= 0 stops the loop. 5 goes at index -1 + 1 = 0.

Before an insertion, the program must also check size < len(a): with no spare cell left, the first shift would write a[len(a)] and stop with an IndexError.

Inserting 22: shifts from the right, then line 8 writes into the gapindex0123456startshift 1shift 2shift 3line 81219253140001219253140400121925313140012192525314001219222531400

Exercise 5: Deleting from the middle: shifting to the left, then size - 1

11 answers to check

The array a uses the same convention as in exercise 4: size counts the cells in use, from index 0. To delete the element at index pos, the program moves every later cell one step to the left, then counts one cell fewer.

Python
a = [36, 11, 58, 27, 90, 44, 0]    # line 1
size = 6                           # line 2
pos = 2                            # line 3
for i in range(pos, size - 1):     # line 4
    a[i] = a[i + 1]                # line 5
size = size - 1                    # line 6
for i in range(size):              # line 7
    print(a[i])                    # line 8
  • a) How many times does line 5 run? Which value is no longer in the array?
  • b) After the loop of lines 4 and 5, give a[2], a[4] and a[5].
  • c) Line 6 is forgotten. How many lines do lines 7 and 8 print? Which value is printed twice?
  • d) Another student shifts in the other direction: for i in range(size - 2, pos - 1, -1): a[i] = a[i + 1], from the right. After his loop, what is a[2]? Of the values 27, 90 and 44, how many are still in cells 0 to 4?
  • e) From line 1 again, pos = 5, the last cell in use: how many times does line 5 run? Same question for pos = 0.

Type your answers, the page tells you right or wrong 0/11

a)
b)
c)
d)
e)
Show the solution

Answers

  • a) 3 times; 58 is gone
  • b) a[2] = 27, a[4] = 44, a[5] = 44
  • c) 6 lines; 44 is printed twice
  • d) a[2] = 44; only 1 of the three values is left, 44
  • e) 0 times for pos = 5; 5 times for pos = 0

Deleting is the mirror of inserting: the cells move to the left, so the loop runs from pos upwards, and each copy goes into the cell copied just before. The drawing shows the array after each shift.

a)

range(2, 5) gives 2, 3 and 4: line 5 runs 3 times, size - 1 - pos.

i = 2: a[2] = a[3] = 27, and 58 is overwritten: it is the deleted value. i = 3: a[3] = 90. i = 4: a[4] = 44.

b)

a[2] = 27 and a[4] = 44. a[5] was never assigned and still holds 44.

The array is [36, 11, 27, 90, 44, 44, 0]. The second 44 does no harm once size is 5, because cell 5 is no longer in use.

c)

Without line 6, size stays 6 and lines 7 and 8 print a[0] to a[5]: 36, 11, 27, 90, 44, 44, 6 lines.

Pitfall: a deletion that does not reduce size leaves the last value twice. The shifts are right; the count of cells in use is wrong.

d)

range(4, 1, -1) gives 4, 3, 2. i = 4: a[4] = a[5] = 44. i = 3: a[3] = a[4], which is now 44. i = 2: a[2] = a[3] = 44.

The array is [36, 11, 44, 44, 44, 44, 0]: a[2] = 44, and 27 and 90 are lost. Of 27, 90 and 44, only 44 is left in cells 0 to 4.

Pitfall: shifting in the wrong direction copies one value over all the others. For a deletion, the loop goes from pos up to size - 2; for an insertion, from size - 1 down.

e)

pos = 5: range(5, 5) is empty, line 5 runs 0 times. size - 1 is enough: the last cell is simply no longer in use.

pos = 0: range(0, 5) gives 0 to 4, line 5 runs 5 times, the most for this array. Deleting near the start costs the most shifts.

Deleting a[2] = 58: shifts to the left, from pos to size - 2index0123456startshift 1shift 2shift 3size = 536115827904403611272790440361127909044036112790444403611279044440

Part B: problems and reasoning (/50)

Exercise 6: Three faulty searches: a conclusion drawn from one element

10 answers to check

Three students wrote a linear search in an array of names. Each version runs with no error message. Each part runs one version alone, after the first two lines.

Python
names = ['Ava', 'Noah', 'Zoe', 'Liam', 'Mia']
wanted = input('Name: ')

# Version A
for i in range(len(names)):
    if names[i] == wanted:
        print('Found at index', i)
    else:
        print('Not found')

# Version B
found = False
for i in range(len(names)):
    if names[i] == wanted:
        found = True
    else:
        found = False
print(found)

# Version C
pos = -1
for i in range(len(names) - 1):
    if names[i] == wanted:
        pos = i
print(pos)
  • a) Version A, the user types Zoe. How many lines are printed? How many of them say Not found?
  • b) Version B, the user types Zoe, then, in a second run, Mia. What does it print each time?
  • c) Version C, the user types Zoe, then Mia. What does it print each time? Which name of the list can version C never find?
  • d) In a correct search, where does the line that prints Not found go?
  • e) Write a correct version that stops as soon as the name is found and prints one line. How many comparisons names[i] == wanted does it make for Liam? For Eli, who is not in the list?

Type your answers, the page tells you right or wrong 0/10

a)
b)
c)
d)
e)
Show the solution

Answers

  • a) 5 lines, 4 of them Not found
  • b) False for Zoe, True for Mia
  • c) 2 for Zoe, -1 for Mia; Mia can never be found
  • d) After the loop, under if pos == -1:
  • e) 4 comparisons for Liam, 5 for Eli

« Not found » is a statement about every element, so it can only be concluded after the last one has been compared. Versions A and B conclude from one element, version C stops one element too early. The program above is a correct version; the table below sums up the runs.

a)

Version A prints one line per pass, whatever the element: Not found for Ava and Noah, Found at index 2 for Zoe, then Not found for Liam and Mia.

5 lines, 4 of them Not found, although Zoe is in the list.

Pitfall: else: print('Not found') inside the loop concludes « absent » from a single element, here from the very first one, Ava.

b)

Version B rewrites found at every pass, so after the loop it describes the last element only.

Zoe: True at i = 2, then False at i = 3 and i = 4. It prints False.

Mia: False, False, False, False, then True at i = 4. It prints True, but only because Mia is last.

The else must go: found starts at False before the loop, and only a match changes it.

c)

range(len(names) - 1) gives 0 to 3: names[4] is never compared.

Zoe is at index 2: it prints 2. Mia is at index 4: it prints -1.

Mia, the last name, can never be found. Pitfall: a search that stops too early; the indices of a traversal go up to len(names) - 1, so the stop of range is len(names).

d)

After the loop, under if pos == -1:, as in the program above. Only then has every element been compared.

e)

The while loop stops when pos changes. Liam is at index 3: Ava, Noah, Zoe, Liam, 4 comparisons, and it prints Found at index 3.

Eli matches no element: 5 comparisons, one per name, then pos is still -1 and it prints Not found once.

In Java, two strings are compared with names[i].equals(wanted); == compares whether they are the same object.

Python
names = ['Ava', 'Noah', 'Zoe', 'Liam', 'Mia']
wanted = input('Name: ')
pos = -1
i = 0
while i < len(names) and pos == -1:
    if names[i] == wanted:
        pos = i
    i = i + 1
if pos == -1:
    print('Not found')
else:
    print('Found at index', pos)
Versionwanted = 'Zoe'wanted = 'Mia'A, else prints5 lines, 4 of them Not found5 lines, 4 of them Not foundB, flag resetFalseTrueC, len(names) - 12-1while, pos == -12, after 3 comparisons4, after 5 comparisonsWhat each version prints; in red, a wrong conclusion

Exercise 7: Problem: a losing soccer season, and a maximum that starts at 0

8 answers to check

An under-16 soccer team lost its first six games. For each game, the coach stores the goal differential, goals for minus goals against, in diff: -3 means a loss by three goals. A student wrote the program below to report the closest game, the one with the highest differential, numbered from 1, and the average differential.

-3-1-2-1-4-1diffindexgameGoals for minus goals against: six losses, no value above 0011223344556
Python
diff = [-3, -1, -2, -1, -4, -1]         # line 1
best = 0                                # line 2
game = 0                                # line 3
total = 0                               # line 4
for i in range(len(diff)):              # line 5
    total = total + diff[i]             # line 6
    if diff[i] > best:                  # line 7
        best = diff[i]                  # line 8
        game = i + 1                    # line 9
print('Closest game:', game, best)      # line 10
print('Average:', total / len(diff))    # line 11
  • a) What does line 10 print as the game number, and as the differential?
  • b) Which change to lines 2 and 3 corrects the program for any array of differentials? After the change, what does line 10 print?
  • c) What does line 11 print as the average?
  • d) Before the first game, diff is []. With the correction of b), what happens when the program runs?
  • e) Write the lines that count the games lost by 3 goals or more. What is the count for this season?

Type your answers, the page tells you right or wrong 0/8

a)
b)
c)
d)
e)
Show the solution

Answers

  • a) Game 0 and differential 0: a game and a value that do not exist
  • b) best = diff[0] and game = 1; line 10 then prints game 2, differential -1
  • c) -2.0
  • d) Line 2 stops the program with an IndexError; a guard if len(diff) == 0 must come first
  • e) 2 games, the -3 and the -4

Every value of diff is negative, so a maximum started at 0 is never beaten. The table compares the two starts pass by pass; the program above is the corrected version, with the guard of part d) and the count of part e).

a)

Line 7 compares -3, -1, -2, -1, -4 and -1 with best = 0: each test is False, so lines 8 and 9 never run.

Line 10 prints Closest game: 0 0. There is no game 0, and no game ended with a differential of 0.

Pitfall: a maximum started at 0 gives 0 for an array of negative values, a value that is not in the array, and the program shows no error.

b)

best = diff[0] and game = 1: the first game is the best seen before any comparison, and it is game number 1.

Pass i = 1: -1 > -3, best = -1 and game = 2. Then -2, -1, -4 and -1 are not strictly greater than -1.

Line 10 prints Closest game: 2 -1. Games 4 and 6 also ended at -1; with >, the report keeps the first of them. Check: max(diff) gives -1.

best = -1 or best = -100 would also give -1 here, but they depend on the data: a season where every game is lost by more than one goal would make best = -1 answer -1 again, a value not in the array. A start taken from the array works for every array that is not empty.

c)

total = -3 - 1 - 2 - 1 - 4 - 1 = -12, and len(diff) = 6: line 11 prints Average: -2.0.

A negative average is a normal value here: it says the team lost by two goals per game on average.

d)

With diff = [], line 2 reads diff[0], a cell that an empty array does not have: IndexError on line 2, before the loop.

Without the correction, the program would have run up to line 11 and stopped there with a ZeroDivisionError, 0 / 0.

Pitfall: an empty array has no largest value and no average. The program above tests len(diff) == 0 first and prints a message instead.

e)

Lost by 3 goals or more means a differential of -3 or less: the test is diff[i] <= -3, inside the same loop, with big_losses = 0 before it.

-3 and -4 pass the test: 2 games.

diff[i] < -3 would leave out the -3 game and give 1; diff[i] >= 3 counts wins by 3 or more, 0 here.

Python
diff = [-3, -1, -2, -1, -4, -1]
if len(diff) == 0:
    print('No games played yet')
else:
    best = diff[0]
    game = 1
    total = 0
    big_losses = 0
    for i in range(len(diff)):
        total = total + diff[i]
        if diff[i] > best:
            best = diff[i]
            game = i + 1
        if diff[i] <= -3:
            big_losses = big_losses + 1
    print('Closest game:', game, best)
    print('Average:', total / len(diff))
    print('Lost by 3 or more:', big_losses)
idiff[i]best = 0gamebest = diff[0]game0-300-311-100-122-200-123-100-124-400-125-100-12best after each pass: from 0 (red) and from diff[0] (green)

Exercise 8: Five statements to correct

10 answers to check

Each statement below was written by a student. Say whether it is true or false, answer the question that checks it, and correct the false ones. In b), a comparison is one test of an element against the target. In c) and d), size counts the cells in use, as in exercises 4 and 5.

  • a) « To find the largest value of an array, start with largest = 0. » What would this start give as the largest value of [-5, -2, -9]?
  • b) « A linear search for a value that is absent from an array of 8 elements makes 8 comparisons. » How many comparisons does it make?
  • c) « To insert into a sorted array, shift the cells from the left, starting at the insertion index. » With a = [3, 6, 9, 0] and size = 3, 5 goes at index 1. After for j in range(1, size): a[j + 1] = a[j], then a[1] = 5, what does a[3] hold?
  • d) « Deleting the element at index pos by shifting to the left takes size - 1 - pos shifts. » With a = [5, 7, 9, 11, 0], size = 4 and pos = 1, how many shifts are there?
  • e) « total / len(a) gives the average of any array a. » What does the program do with a = []?

Type your answers, the page tells you right or wrong 0/10

a)
b)
c)
d)
e)
Show the solution

Answers

  • a) False: it gives 0, a value not in the array; start from a[0], which gives -2
  • b) True: 8 comparisons
  • c) False: a = [3, 5, 6, 6], a[3] = 6 and 9 is lost; shift from the right
  • d) True: 2 shifts
  • e) False: a ZeroDivisionError; test len(a) > 0 first
a)

False. -5, -2 and -9 are all below 0, so no comparison beats the start, and the program answers 0, a value that is not in the array.

Correct statement: « Start with largest = a[0], the first element. » For [-5, -2, -9] it gives -2.

b)

True. A value that is absent can only be declared absent after every element has been compared: 8 comparisons, one per element.

A value that is present costs fewer, its index plus 1, when the search stops at the first match.

c)

False. j = 1: a[2] = a[1] = 6, and 9 is overwritten. j = 2: a[3] = a[2], which is now 6. Then a[1] = 5.

a = [3, 5, 6, 6]: a[3] = 6, and 9 is lost.

Correct statement: « Shift the cells from the right, from size - 1 down to the insertion index. » From the right, a = [3, 5, 6, 9].

d)

True. The cells pos + 1 to size - 1 each move one step to the left: indices 2 and 3 here, 4 - 1 - 1 = 2 shifts.

a becomes [5, 9, 11, 11, 0] and size 3: the second 11 is outside the cells in use.

e)

False. With a = [], total = 0 and len(a) = 0: 0 / 0 stops the program with a ZeroDivisionError.

Correct statement: « total / len(a) gives the average of a non-empty array; test len(a) > 0 first. »

Exercise 9: Problem: the high-score table of an arcade game

12 answers to check

An arcade game keeps its eight best scores in an array, from the highest to the lowest. The table is always full. Specification: a new score enters the table only if it is strictly higher than the lowest score of the table; it then takes its place in order, and the lowest score leaves the table. On a tie, the older score keeps the higher rank. A student wrote the program below.

98508720810076406900521048753300scoresindexrankEight cells, all in use, from the highest score to the lowest0112233445566778
Python
scores = [9850, 8720, 8100, 7640, 6900, 5210, 4875, 3300]    # line 1
new = int(input('Score: '))                                  # line 2
if new > scores[len(scores) - 1]:                            # line 3
    i = len(scores) - 2                                      # line 4
    while i >= 0 and scores[i] < new:                        # line 5
        scores[i + 1] = scores[i]                            # line 6
        i = i - 1                                            # line 7
    scores[i + 1] = new                                      # line 8
print(scores)                                                # line 9
  • a) The new score is 3000. Does the table change? And for a new score of 3300?
  • b) The new score is 7000. How many times does line 6 run? At which index does line 8 write 7000? Which score leaves the table?
  • c) The new score is 8100, a tie with a score already in the table. At which index does it go? Which comparison on line 5 respects the specification? With the other one, at which index would 8100 go?
  • d) Another student first finds that 7000 goes at index 4, then writes for j in range(4, len(scores) - 1): scores[j + 1] = scores[j], then scores[4] = new. In how many cells does 6900 appear at the end? What does scores[7] hold?
  • e) The new score is 10200. How many times does line 6 run? What does i hold when the loop stops?

Type your answers, the page tells you right or wrong 0/12

a)
b)
c)
d)
e)
Show the solution

Answers

  • a) No for 3000; no for 3300, a tie with the lowest score does not enter
  • b) 3 shifts; index 4 (rank 5); 3300 leaves the table
  • c) Index 3, after the older 8100; the comparison <; with <= it would go at index 2
  • d) 6900 appears in 3 cells; scores[7] = 6900
  • e) 7 shifts; i = -1

The table is sorted from the highest score, so the shifts move every score lower than the new one one rank down. The loop starts at index len(scores) - 2 = 6: the copy into scores[7] overwrites the lowest score, the one that must leave. The program above is the same algorithm with messages; the drawing shows part b), from the right and from the left.

a)

Line 3 tests new > scores[7], that is new > 3300. 3000 > 3300 is False: nothing changes.

3300 > 3300 is False too: a tie with the lowest score does not enter, as the specification says (strictly higher). The table does not change in either case.

b)

7000 > 3300, so i = 6.

i = 6: 4875 < 7000, scores[7] = 4875 and 3300 is gone. i = 5: 5210 < 7000, scores[6] = 5210. i = 4: 6900 < 7000, scores[5] = 6900. i = 3: 7640 < 7000 is False.

Line 6 ran 3 times, and line 8 writes 7000 at index i + 1 = 4, rank 5.

The table becomes [9850, 8720, 8100, 7640, 7000, 6900, 5210, 4875]: 3300 left it, and the order is kept.

c)

With <: the loop moves 4875, 5210, 6900 and 7640 one rank down, then stops at i = 2, where 8100 < 8100 is False. The new 8100 goes at index 3, just after the older one.

The comparison < respects the specification: the older 8100 keeps rank 3.

With <=, 8100 <= 8100 is True: the older 8100 is shifted too, the loop stops at i = 1, and the new score goes at index 2, ahead of the older one.

Pitfall: on a tie, < against <= decides who gets the higher rank. The specification decides, not the code.

d)

j = 4: scores[5] = scores[4] = 6900, and 5210 is overwritten. j = 5: scores[6] = scores[5], now 6900, and 4875 is overwritten. j = 6: scores[7] = 6900. Then scores[4] = 7000.

The table ends as [9850, 8720, 8100, 7640, 7000, 6900, 6900, 6900]: 6900 is in 3 cells, scores[7] = 6900, and 5210 and 4875 are lost with 3300.

Pitfall: shifting from the left, from the insertion index, copies one value over every later cell. Shift from the right, as lines 4 to 7 do.

e)

10200 beats every score: the loop shifts all 7 scores from index 6 down to index 0, so line 6 runs 7 times, and i ends at -1.

The test i >= 0 stops the loop, and line 8 writes scores[0] = 10200, rank 1.

The order of the test matters. Written scores[i] < new and i >= 0, the loop would read scores[-1] at i = -1. Python reads it as the last cell, here 4875, and the loop still stops on i >= 0; Java stops the program with an ArrayIndexOutOfBoundsException. Test the index first.

Python
scores = [9850, 8720, 8100, 7640, 6900, 5210, 4875, 3300]
new = int(input('Score: '))
if new > scores[len(scores) - 1]:
    i = len(scores) - 2
    while i >= 0 and scores[i] < new:
        scores[i + 1] = scores[i]
        i = i - 1
    scores[i + 1] = new
    print('New high score, rank', i + 2)
else:
    print('Not in the top 8')
for k in range(len(scores)):
    print(k + 1, scores[k])
Inserting 7000, shifted from the right or from the leftindex01234567beforefrom the rightfrom the left985087208100764069005210487533009850872081007640700069005210487598508720810076407000690069006900

Exercise 10: Problem: a student leaves the waitlist of a ski trip

11 answers to check

The bus of a school ski trip is full, and the office keeps a waitlist of student numbers, in the order the students signed up: the first one gets the next free seat. The array has 10 cells and size counts the students on the list. When a student leaves the list, the program finds the student number by a linear search, then deletes it by shifting the later cells to the left, so that the order of the others is kept. A comparison is one test on line 7.

index0123456789wait4417309255812260603417980000size = 6: cells 0 to 5 in use, four spare cells (grey)
Python
wait = [4417, 3092, 5581, 2260, 6034, 1798, 0, 0, 0, 0]    # line 1
size = 6                                                   # line 2
leaving = int(input('Student number: '))                   # line 3
pos = -1                                                   # line 4
i = 0                                                      # line 5
while i < size and pos == -1:                              # line 6
    if wait[i] == leaving:                                 # line 7
        pos = i                                            # line 8
    i = i + 1                                              # line 9
for k in range(pos, size - 1):                             # line 10
    wait[k] = wait[k + 1]                                  # line 11
size = size - 1                                            # line 12
for k in range(size):                                      # line 13
    print(wait[k])                                         # line 14
  • a) The student 2260 leaves. What is pos after the search? How many comparisons are made?
  • b) Still for 2260: how many times does line 11 run? How many lines are printed? What does wait[3] hold at the end?
  • c) The office types 2206 by mistake, a number that is not on the list. How many comparisons are made? The program shows no error: what is the first line printed? Which student number is no longer on the list?
  • d) Which change corrects the program of part c)?
  • e) Back to 2260, but line 12 is forgotten. How many lines are printed? Which student number is printed twice?

Type your answers, the page tells you right or wrong 0/11

a)
b)
c)
d)
e)
Show the solution

Answers

  • a) pos = 3, after 4 comparisons
  • b) 2 shifts; 5 lines; wait[3] = 6034
  • c) 6 comparisons; the first line is 3092; 4417 was removed, the first student on the list
  • d) Shift and subtract 1 only if pos != -1, under if pos == -1: print('Not on the waitlist') else: ...
  • e) 6 lines; 1798 is printed twice

The program chains two algorithms: a search that gives a position or -1, then a deletion that uses that position as an index. The second one must not run on -1. The program above is the corrected version; the drawing shows what the faulty one does to the list in part c).

a)

i = 0: 4417 == 2260 False; i = 1: 3092 False; i = 2: 5581 False; i = 3: 2260 == 2260 True, pos = 3.

The loop stops, since pos == -1 is now False: pos = 3, after 4 comparisons.

b)

range(3, 5) gives 3 and 4: wait[3] = wait[4] = 6034, then wait[4] = wait[5] = 1798. Line 11 runs 2 times.

size becomes 5, and lines 13 and 14 print 4417, 3092, 5581, 6034 and 1798: 5 lines, in sign-up order. wait[3] = 6034.

c)

2206 matches none of the 6 students: 6 comparisons, and pos stays -1.

Line 10 then runs range(-1, 5), which gives -1, 0, 1, 2, 3, 4. At k = -1, wait[-1] = wait[0]: in Python, wait[-1] is the last cell, wait[9], a spare cell, so the program shows no error. At k = 0 to 4, every student moves one cell to the left.

size becomes 5, and the program prints 3092, 5581, 2260, 6034, 1798: the first line is 3092, and 4417, the student first in line for a seat, is no longer on the list.

Pitfall: the position -1 used as an index. In Java, wait[-1] would stop the program with an ArrayIndexOutOfBoundsException; Python reads the last cell, without a word.

d)

The deletion, lines 10 to 12, runs only if pos != -1. Under if pos == -1:, the program prints a message such as Not on the waitlist, and the list is left as it is, as in the program above.

e)

Without line 12, size stays 6, and lines 13 and 14 print wait[0] to wait[5]: 4417, 3092, 5581, 6034, 1798, 1798.

6 lines, and 1798 is printed twice. The next student to sign up would be written into wait[6], and 1798 would stay on the list twice.

Pitfall: a deletion that does not reduce size leaves the last value twice.

Python
wait = [4417, 3092, 5581, 2260, 6034, 1798, 0, 0, 0, 0]
size = 6
leaving = int(input('Student number: '))
pos = -1
i = 0
while i < size and pos == -1:
    if wait[i] == leaving:
        pos = i
    i = i + 1
if pos == -1:
    print('Not on the waitlist')
else:
    for k in range(pos, size - 1):
        wait[k] = wait[k + 1]
    size = size - 1
for k in range(size):
    print(wait[k])
Typo 2206: range(-1, 5) writes wait[-1], then shifts everyone leftindex0123456789beforepos = -144173092558122606034179800003092558122606034179817980004417
Something missing from this set? A type of exercise your teacher gives, a problem you are stuck on, a mistake you spotted: tell me, I read every request.

Sending goes through your free space: that is how I can answer you and tell you when the exercise is added. An email is enough, no password. Create your space. Rather not create an account? Write to me directly.

What is it about?
I read every request myself, nobody else sees it. No need to write your name or your school.
When your request is dealt with, you hear about it by email and in your space.

By sending, you agree that I read your request to answer it. It is kept with your account, erased with it, and never published: privacy policy.

© Ahmed Squalli Houssaini. Exercise set published at www.letuteurscientifique.ca/en/exercices/ics3u-array-algorithms. Free for personal and classroom use; republishing it elsewhere requires written permission (legal notice).

Preparing for an ICS3U unit test?

I tutor Grade 11 computer science in English or in French, online. Get in touch for a first session: counting, searching, inserting and deleting come back in every program of the course, up to the final project.

Site by Studio Squalli