ICS3U Computer Science • Ontario Grade 11

Corrected exercises: one-dimensional arrays (ICS3U)

Exercises: one-dimensional arrays (ICS3U)

Name: Class: Date:

Solutions

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

These ten corrected exercises cover the fifth chapter of ICS3U, Introduction to Computer Science, Grade 11, University Preparation, in Ontario: one-dimensional arrays, called lists in Python.

What the set covers, the traps it targets

You declare an array of a given size, initialize it, read and change its elements by index, stay within its bounds, traverse it with a loop over the indices or over the elements, fill it from the keyboard, tell a second name from a copy, and keep two parallel arrays aligned.

The code is in Python 3; indices, bounds, traces and references are reasoned the same way in any language, and a line of the solutions says where Java behaves differently.

By the end, you can read the cells and the bounds of an array (exercise 1), follow an array line by line through its assignments (exercise 2), trace a traversal that changes every cell and find the index that goes too far (exercise 3), explain why for x in a: x = 0 changes nothing (exercise 4), and tell a second name from a copy (exercise 5). Part B fills an array from the keyboard and prints it backwards (exercise 6), keeps the stops and the riders of a school bus route aligned (exercise 7), corrects five statements (exercise 8), copies a thermostat schedule without changing the original (exercise 9), and guards the level numbers of a parking garage (exercise 10).

The thread of the set: every change to an array goes through a cell, a[i] = value, with i from 0 to len(a) - 1. Five traps are named in the solutions: (1) taking len(a) for a valid index, when the last one is len(a) - 1, exercises 1, 2, 3, 6 and 8; (2) expecting for x in a: x = 0 to change the array, exercises 4, 8 and 9; (3) reading b = a as a copy, when both names refer to one array, exercises 5, 8 and 9; (4) a negative index, valid in Python and an error in Java, exercises 1 and 10; (5) parallel arrays changed on one side only, so that a name no longer has its number, exercise 7. Elements used as indices (exercise 4), writing into an empty list (exercise 2), a traversal that starts at 1 (exercises 3, 6 and 8) and a number from 1 used as an index (exercise 10) come back as well.

No calculator is needed: every index, every trace and every output is worked out by hand, as on a unit test. Counting, totals, the largest value, linear search, insertion and deletion belong to array algorithms, a later unit of the course.

  • 10 corrected exercises • 100 points • 150 minutes
  • Self-checking, 106 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

  • • A one-dimensional array, a list in Python, is a row of cells under one name, reached by index: a[0] is the first cell, a[len(a) - 1] the last.
  • • [0] * n creates n cells holding 0; [] has no cell at all.
  • • a[i] = value changes one cell; an index outside 0 to len(a) - 1 raises an IndexError.
  • • for i in range(len(a)) gives the indices: it can read and change the cells.
  • • for x in a gives a copy of each value: assigning to x reads the array but never changes a cell.
  • • b = a gives the same array a second name; a copy needs new cells, filled by a loop over the indices.
  • • Parallel arrays: the same index describes the same item in every array, so every change is made in all of them.
  • • Python accepts a negative index, counted from the end; Java stops with an error.

Part A: the basics (/50)

Exercise 1: Cells, indices and bounds: reading a one-dimensional array

13 answers to check

A one-dimensional array, a list in Python, stores several values under one name. Each value sits in a cell, and a cell is reached by its index, written in square brackets: data[0] is the first cell. The bounds of an array are its first and last valid indices.

Python
data = [52, 47, 61, 49, 55, 58, 50]    # line 1
  • a) How many elements does data hold? What are its first and last valid indices?
  • b) Give the values of data[0], data[3] and data[len(data) - 1].
  • c) Which whole numbers i make data[i] a valid cell? What happens when the program runs print(data[7])?
  • d) After i = 2, give the values of data[i + 3], data[2 * i] and data[i] + data[i + 1].
  • e) Python also accepts print(data[-1]). What does it print? In Java, an array with the same values is declared int[] data = {52, 47, 61, 49, 55, 58, 50}. What does data[-1] do there?

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

a)
b)
c)
Valid indices ,
d)
e)
Show the solution

Answers

  • a) 7 elements; first index 0, last index 6
  • b) data[0] = 52, data[3] = 49, data[len(data) - 1] = 50
  • c) The indices 0 to 6, {i ∈ ℤ | 0 ≤ i ≤ 6}; print(data[7]) stops the program with an IndexError
  • d) 58, 55 and 110
  • e) 50 in Python; in Java the program stops with an ArrayIndexOutOfBoundsException

Number the cells from 0 before reading anything: the drawing below shows data with its indices under the cells.

a)

len(data) counts the elements: 7.

The first index is 0, so the last one is len(data) - 1 = 6: seven cells, numbered 0 to 6.

b)

data[0] = 52, the first cell.

data[3] = 49: index 3 is the fourth cell, after the indices 0, 1 and 2.

data[len(data) - 1] = data[6] = 50. This expression gives the last element of an array of any length.

Pitfall: reading data[3] as the third element, 61. Index and position differ by one: the element in position k has the index k - 1.

c)

The valid indices are the whole numbers from 0 to 6, {i ∈ ℤ | 0 ≤ i ≤ 6}: they are the bounds of data.

print(data[7]) asks for an eighth cell, which does not exist. Python stops the program with IndexError: list index out of range, and that line prints nothing.

Pitfall: taking len(data), here 7, for the last index. len counts the cells; the last index is one less.

d)

The index is computed first, then the cell is read.

data[i + 3] = data[5] = 58.

data[2 * i] = data[4] = 55.

data[i] + data[i + 1] = data[2] + data[3] = 61 + 49 = 110: two cells are read, then added. data[i + 1] is the cell after data[i], not data[i] plus 1.

e)

In Python, a negative index counts from the end: data[-1] is the last cell, 50, and data[-7] is the first, 52.

In Java, an index below 0 is outside the bounds: data[-1] stops the program with an ArrayIndexOutOfBoundsException.

Pitfall: a negative index produced by a mistake, such as i - 1 with i = 0, gives no error in Python: it reads the last cell without a word. Apart from one bug traced in exercise 10, the rest of this set uses indices from 0 to len - 1 only.

5204716124935545855067data[7]: IndexErrordata: 7 cells, indices 0 to len(data) - 1 = 6

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: Declaring, initializing and changing cells: an array line by line

11 answers to check

[0] * n creates an array of n cells that all hold 0: it is how a Python program declares an array of a given size. An assignment a[i] = value changes one cell and leaves the others as they are. The index can be any expression whose value is a valid index.

Python
a = [0] * 6                # line 1
a[0] = 4                   # line 2
a[5] = a[0] * 3            # line 3
a[2] = a[5] - a[0]         # line 4
a[0] = a[0] + 1            # line 5
i = 3                      # line 6
a[i] = i * 2               # line 7
a[i + 1] = a[i] + a[2]     # line 8
print(a)                   # line 9
  • a) After line 1, how many cells does a have, and what does each cell hold?
  • b) Trace lines 2 to 8. Give a[2], a[4] and a[5] after line 8.
  • c) What does line 9 print?
  • d) A line 10, a[6] = 1, is added. What happens when it runs? Which index would a[len(a) - 1] = 1 change instead?
  • e) A student writes scores = [] and then scores[0] = 7. What happens? How many elements do [7] * 3 and [7 * 3] hold?

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

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

Answers

  • a) 6 cells, each holding 0
  • b) a[2] = 8, a[4] = 14, a[5] = 12
  • c) [5, 0, 8, 6, 14, 12]
  • d) IndexError: list assignment index out of range; a[len(a) - 1] changes index 5
  • e) An IndexError: an empty list has no cell 0; 3 elements and 1 element

Each assignment changes one cell; a trace writes the whole array after each line. The table below follows a from line 1 to line 8, with the cell changed by each line in green.

a)

[0] * 6 repeats the one-cell array [0] six times: a = [0, 0, 0, 0, 0, 0], 6 cells with the indices 0 to 5, each holding 0.

b)

Line 2: a[0] = 4.

Line 3: a[5] = a[0] * 3 = 4 × 3 = 12. The right side is computed first, with a[0] as it is now.

Line 4: a[2] = a[5] - a[0] = 12 - 4 = 8.

Line 5: a[0] = a[0] + 1 = 5. Lines 3 and 4 already used the old value 4; changing a[0] now does not go back and change them.

Lines 6 and 7: i = 3, so a[3] = 3 × 2 = 6.

Line 8: a[i + 1] is a[4] = a[3] + a[2] = 6 + 8 = 14.

After line 8: a[2] = 8, a[4] = 14 and a[5] = 12.

c)

a[1] was never assigned and keeps its 0. Python prints the list with its brackets: [5, 0, 8, 6, 14, 12].

d)

a has 6 cells, indices 0 to 5, and a[6] = 1 asks for a seventh. A Python list does not grow on an assignment: the program stops with IndexError: list assignment index out of range.

a[len(a) - 1] = 1 is a[5] = 1: it changes the last cell, index 5.

Pitfall: len(a), here 6, is never a valid index of a.

e)

scores = [] is an array with no cell at all, so scores[0] = 7 also stops the program with an IndexError. Create the cells first, scores = [0] * 3, then assign; or grow the list at its end with scores.append(7), a Python method that adds one cell.

[7] * 3 = [7, 7, 7]: 3 elements. [7 * 3] = [21]: 1 element, since the product is computed inside the brackets.

Linea[0]a[1]a[2]a[3]a[4]a[5]100000024000003400001244080012550800126 (i = 3)508001275086012850861412a after each line; in green, the cell the line changed

Exercise 3: A traversal by index: for i in range(len(data)) changes every cell

13 answers to check

To visit every cell, a loop runs over the indices: for i in range(len(data)): gives i = 0, 1, and so on up to len(data) - 1, which are the valid indices. In the body, data[i] is the current cell, and an assignment to data[i] changes it.

Python
data = [3, 8, 2, 7, 5]             # line 1
for i in range(len(data)):         # line 2
    data[i] = data[i] * 2 + i      # line 3
print(data)                        # line 4
  • a) How many passes does the loop make? Which values does i take first and last?
  • b) Trace the loop. Give data[1] and data[4] after it. What does line 4 print?
  • c) Line 2 becomes for i in range(1, len(data)):. How many passes does the loop make, and what does data[0] hold at the end?
  • d) Line 2 becomes for i in range(len(data) + 1): instead. For which value of i does the program stop? Does line 4 run?
  • e) A loop that reads data[i + 1] must stop one index earlier. Which header is right for it? Starting again from line 1, what do data[1] and data[4] hold after the loop for i in range(len(data) - 1): data[i] = data[i + 1] - data[i]?

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

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

Answers

  • a) 5 passes; i = 0 first, i = 4 last
  • b) data[1] = 17, data[4] = 14; line 4 prints [6, 17, 6, 17, 14]
  • c) 4 passes; data[0] = 3
  • d) It stops at i = 5 with an IndexError on line 3; line 4 does not run
  • e) for i in range(len(data) - 1):; data[1] = -6, data[4] = 5

range(len(data)) gives the valid indices in order, so data[i] visits each cell once. The trace is below.

a)

len(data) = 5, so range(5) gives 0, 1, 2, 3, 4: 5 passes, i = 0 first and i = 4 last.

The last value of i is len(data) - 1, the last valid index: range never gives its stop, and that is what keeps i inside the bounds.

b)

Pass 1, i = 0: data[0] = 3 × 2 + 0 = 6.

Pass 2, i = 1: data[1] = 8 × 2 + 1 = 17.

Pass 3, i = 2: data[2] = 2 × 2 + 2 = 6.

Pass 4, i = 3: data[3] = 7 × 2 + 3 = 17.

Pass 5, i = 4: data[4] = 5 × 2 + 4 = 14.

Line 4 prints [6, 17, 6, 17, 14]: the cells were changed in place, through data[i].

c)

range(1, 5) gives 1, 2, 3, 4: 4 passes. Index 0 is never visited, so data[0] keeps 3, and line 4 prints [3, 17, 6, 17, 14].

Pitfall: starting a traversal at 1 because people count from 1. The first cell is index 0.

d)

range(6) gives 0 to 5. Passes 1 to 5 change the five cells; on pass 6, i = 5 and data[5] does not exist: IndexError: list index out of range, on line 3.

The program stops there, so line 4 never runs and nothing is printed, although the five cells were already changed.

Pitfall: a stop of len(data) + 1 visits one index too many. The stop of range is len(data), the one value range never gives.

e)

data[i + 1] is a valid cell only while i + 1 ≤ len(data) - 1, that is i ≤ len(data) - 2. The header is for i in range(len(data) - 1):, which gives 0 to 3. With range(len(data)), the last pass would read data[5] and stop the program.

From data = [3, 8, 2, 7, 5]: i = 0 gives data[0] = 8 - 3 = 5; i = 1 gives data[1] = 2 - 8 = -6; i = 2 gives data[2] = 7 - 2 = 5; i = 3 gives data[3] = 5 - 7 = -2.

Each pass reads data[i + 1] before the loop reaches that cell, so the value read is still the one of line 1.

data[4] is never assigned and keeps 5: data = [5, -6, 5, -2, 5].

Passidata[i] beforeline 3data after the pass1033 × 2 + 0 = 6[6, 8, 2, 7, 5]2188 × 2 + 1 = 17[6, 17, 2, 7, 5]3222 × 2 + 2 = 6[6, 17, 6, 7, 5]4377 × 2 + 3 = 17[6, 17, 6, 17, 5]5455 × 2 + 4 = 14[6, 17, 6, 17, 14]One pass per index, from 0 to len(data) - 1 = 4

Exercise 4: for x in stock: x receives a copy, and the array does not change

7 answers to check

A for loop can also run over the elements themselves: for x in stock: gives x the value of each cell in turn. x is a separate variable that holds a copy of the value; it is not the cell.

Python
stock = [12, 45, 7, 30]     # line 1
for x in stock:             # line 2
    x = x + 10              # line 3
print(stock)                # line 4
print(x)                    # line 5
  • a) What does line 4 print?
  • b) What does line 5 print?
  • c) Which loop adds 10 to every element of stock?
  • d) A student writes for i in stock: stock[i] = stock[i] + 10. What happens on the first pass, and what is the value of i then?
  • e) Can a loop of the form for x in stock: print each element doubled? Can it set every element of stock to 0?

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

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

Answers

  • a) [12, 45, 7, 30]: stock is unchanged
  • b) 40
  • c) for i in range(len(stock)): stock[i] = stock[i] + 10
  • d) i = 12, and stock[12] stops the program with an IndexError
  • e) Yes, it can read the values; no, it cannot change a cell

for x in stock: copies each value into x; only an assignment of the form stock[i] = ... changes a cell. The trace is below.

a)

Pass 1: x = 12, then x = 22. Pass 2: x = 45, then 55. Pass 3: x = 7, then 17. Pass 4: x = 30, then 40.

Each new value goes into x, and the next pass overwrites x with the next element: no cell of stock is touched. Line 4 prints [12, 45, 7, 30].

Pitfall: expecting for x in stock: x = ... to change the array. x holds a copy of the value, not the cell.

b)

After the loop, x keeps its last value, 30 + 10 = 40: line 5 prints 40.

c)

To change a cell, the loop needs its index: for i in range(len(stock)): stock[i] = stock[i] + 10 gives [22, 55, 17, 40].

stock = x + 10 replaces the whole array by a number. The other two loops mix elements and indices, as part d) shows.

d)

for i in stock: gives i the elements 12, 45, 7, 30, not the indices 0 to 3. On the first pass, i = 12, and stock[12] asks for a thirteenth cell in an array of 4: IndexError, before any cell has changed.

Pitfall: naming a variable i does not make it an index. Ask what the loop gives: for x in stock gives values, for i in range(len(stock)) gives indices.

e)

Reading needs only the values: for x in stock: print(x * 2) prints 24, 90, 14 and 60.

Setting the cells to 0 needs the indices: for x in stock: x = 0 leaves stock as it is. Write for i in range(len(stock)): stock[i] = 0.

Passx at the topx after line 3stock11222[12, 45, 7, 30]24555[12, 45, 7, 30]3717[12, 45, 7, 30]43040[12, 45, 7, 30]x changes, stock does not

Exercise 5: b = a gives a second name, not a second array

10 answers to check

An assignment b = a does not copy the array: it gives the same array a second name, and a change made through b is seen through a. To get a separate array, create new cells and copy each value into them.

Python
a = [5, 10, 15]             # line 1
b = a                       # line 2
b[1] = 99                   # line 3
c = [0] * len(a)            # line 4
for i in range(len(a)):     # line 5
    c[i] = a[i]             # line 6
c[0] = -1                   # line 7
print(a, b, c)              # line 8
  • a) After line 3, what does a[1] hold? How many arrays exist in memory after line 2?
  • b) After line 7, give a[0], c[0] and c[1].
  • c) What does line 8 print?
  • d) Two lines are added after line 8: a = [1, 2], then print(b). What do b[0] and len(b) hold?
  • e) Starting again from line 1, which line gives d its own copy of a? How many arrays exist after a = [5, 10, 15], b = a and c = b?

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

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

Answers

  • a) a[1] = 99; one array with two names
  • b) a[0] = 5, c[0] = -1, c[1] = 99
  • c) [5, 99, 15] [5, 99, 15] [-1, 99, 15]
  • d) b[0] = 5 and len(b) = 3: b still names the first array
  • e) d = a[:]; 1 array, with three names

A variable holds a reference to an array, an arrow to its cells. The diagram below shows the memory after line 7.

a)

Line 2 copies the arrow, not the cells: a and b refer to the same array, and only one array exists.

Line 3 changes cell 1 of that array, so a[1] = 99 as well.

Pitfall: reading b = a as « b is a copy of a ». It is two names for one array.

b)

Line 4 creates a second array of 3 cells, [0, 0, 0]. Lines 5 and 6 copy each value of a into it, so c = [5, 99, 15]: the copy is made after line 3, when a[1] is already 99.

Line 7 changes c only: c[0] = -1 while a[0] keeps 5, and c[1] = 99.

c)

a and b print the same array: [5, 99, 15] [5, 99, 15] [-1, 99, 15].

d)

a = [1, 2] creates a new array and points a at it. It does not change the old array, which b still names: b = [5, 99, 15], so b[0] = 5 and len(b) = 3.

A change of a cell, a[0] = ..., is seen through every name of the array; giving a name a new array changes that name only.

e)

In Python, a[:] builds a new array with the same values: a copy in one step, like lines 4 to 6. d = a gives a second name; d = a[0] is the number 5; d = [0] * len(a) creates three cells holding 0, not a copy until a loop fills them.

b = a, then c = b: three names, one array. A change of a cell through a, b or c is seen through the other two.

50991152-10991152abcMemory after line 7: three names, two arraysone array, two namesa second array

Part B: problems and reasoning (/50)

Exercise 6: Filling an array from the keyboard, then printing it backwards

9 answers to check

Write a program that reads a whole number n, then n whole numbers, stores them in an array of n cells, and prints them from the last to the first, one per line. The parts check the lines of your program, then three other ways to write the backward loop.

  • a) Which line creates the array of n cells before the numbers are read?
  • b) The user types 4, then 13, 2, 21 and 8. What does values[2] hold after the numbers are read? What is the first line printed?
  • c) A student writes the backward loop as for i in range(n, 0, -1): print(values[i]). With the same entry, how many lines are printed before the program stops, and for which value of i does it stop?
  • d) Another student writes i = n - 1, then while i > 0: with print(values[i]) and i = i - 1 in the body. How many lines are printed? Which number of the entry is missing?
  • e) A third version prints values[n - 1 - i] in the body of for i in range(n):. Which index is printed on the pass i = 0? On the pass i = 3?

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

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

Answers

  • a) values = [0] * n
  • b) values[2] = 21; the first line printed is 8
  • c) 0 lines; it stops at i = 4 with an IndexError
  • d) 3 lines; 13, stored in values[0], is missing
  • e) Index 3, then index 0

The program has three steps: create n cells, fill them by index, then read them back by index from n - 1 down to 0. The program above is one answer; the drawing below shows the cells for the entry of part b).

a)

values = [0] * n creates n cells, indices 0 to n - 1, before the first read. The loop for i in range(n): then stores the k-th number typed in values[k - 1].

values = [n] is one cell holding n; [] * n repeats an empty list and is still empty, so values[0] = ... would stop the program; n * 0 is the number 0.

b)

values = [13, 2, 21, 8]: the third number typed, 21, is in values[2].

range(n - 1, -1, -1) gives 3, 2, 1, 0: the first line is values[3] = 8, then 21, 2 and 13.

The stop -1 is never given, so 0 is the last index visited: the stop of a decreasing range lies one past the last value wanted.

c)

range(4, 0, -1) gives 4, 3, 2, 1. The first pass reads values[4], a fifth cell in an array of 4: IndexError on the first pass, and no line is printed.

Pitfall: n, the length, is not an index; the last cell is values[n - 1]. This loop would also have skipped values[0], since 0 is its stop.

d)

i takes 3, 2, 1; then the test 0 > 0 is False, so values[0] is never printed. 3 lines, 8, 21 and 2: the first number typed, 13, is missing.

The condition must let i = 0 through: while i >= 0:.

e)

For i = 0, n - 1 - i = 3, the last index; for i = 3, n - 1 - i = 0, the first.

As i goes from 0 to n - 1, n - 1 - i goes from n - 1 down to 0: the same order as the program above, with an increasing range.

Check on the bounds: for every i of range(n), the index n - 1 - i stays between 0 and n - 1.

Python
n = int(input('How many values? '))
values = [0] * n
for i in range(n):
    values[i] = int(input('Value: '))
for i in range(n - 1, -1, -1):
    print(values[i])
13021212834values after the entry 4, then 13, 2, 21, 8range(n - 1, -1, -1) gives 3, 2, 1, 0: every cellrange(n, 0, -1) starts at 4: no cell 4, and 0 is never given

Exercise 7: Parallel arrays on a school bus route: the same index for the same stop

10 answers to check

A school bus route is stored in two parallel arrays: stops[i] is the name of a stop, in the order of the route, and riders[i] is the number of students who board there. The arrays are parallel because one index describes one stop in both: stops[2] and riders[2] are about the same stop. The drawing shows them column by column. Each part starts again from lines 1 and 2.

MapleOakBirchCedarPine60111429374stopsridersindexOne index, one stop: column i is stops[i] and riders[i]
Python
stops = ['Maple', 'Oak', 'Birch', 'Cedar', 'Pine']    # line 1
riders = [6, 11, 4, 9, 7]                             # line 2
for i in range(len(stops)):                           # line 3
    print(stops[i], riders[i])                        # line 4
  • a) At which index is the stop Cedar? How many students board there?
  • b) Lines 3 and 4 are replaced by a loop over range(len(stops)) whose body is if riders[i] >= 8: print(stops[i]). How many lines are printed, and which stops?
  • c) A new stop, Elm, is added at the end of the route by stops.append('Elm'), placed after line 2, and riders is left as it is. How many lines does the loop of lines 3 and 4 print before the program stops? For which value of i does it stop?
  • d) The route changes: Oak and Cedar swap places. A student swaps them in stops only, with three lines placed after line 2: temp = stops[1]; stops[1] = stops[3]; stops[3] = temp. What number does line 4 print next to Oak? Next to Cedar?
  • e) After the change of part c), a student writes line 3 as for i in range(len(riders)):. How many lines are printed? Does the program show an error?

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

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

Answers

  • a) Index 3; 9 students
  • b) 2 lines: Oak, then Cedar
  • c) 5 lines, then an IndexError at i = 5
  • d) Oak 9 and Cedar 11: each stop shows the other one's count
  • e) 5 lines and no error: Elm is left out without a word

Parallel arrays stay correct only while every change is made at the same index in both. The second drawing shows them after the swap of part d).

a)

Cedar is stops[3]; the count of the same stop is at the same index: riders[3] = 9 students.

b)

The loop tests riders[i] for i = 0 to 4 and prints stops[i] at the same index: 11 ≥ 8 for Oak and 9 ≥ 8 for Cedar, while 6, 4 and 7 fail. 2 lines: Oak, then Cedar.

The test reads one array and the output comes from the other: the shared index is what links them.

c)

stops now has 6 cells and riders still 5. range(len(stops)) gives 0 to 5: passes 1 to 5 print Maple 6, Oak 11, Birch 4, Cedar 9 and Pine 7. On the sixth pass, i = 5 and riders[5] does not exist: IndexError.

Pitfall: parallel arrays that no longer have the same length. Each append to one array needs its own append to the other, here riders.append with the count of Elm.

d)

After the swap, stops = ['Maple', 'Cedar', 'Birch', 'Oak', 'Pine'] while riders is still [6, 11, 4, 9, 7]. Line 4 prints Cedar 11 and Oak 9.

Pitfall: a name that no longer has its number. Oak boards 11 students and Cedar 9, but each stop now shows the other one's count, and the program runs without any error.

The fix: swap riders[1] and riders[3] the same way, with a second temporary variable, so that each index again describes one stop.

e)

range(len(riders)) gives 0 to 4: 5 lines, no error, and Elm is never printed.

The program hides the problem instead of showing it. The safe habit: keep both arrays the same length, and check len(stops) == len(riders) when the program is tested.

MapleCedarBirchOakPine60111429374stopsridersindexSwapped in stops only: Cedar now sits over 11, Oak over 9

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.

  • a) « a = [0] * 5 creates an array whose last index is 5. » What is the last index of this array?
  • b) « After a = [8, 8] and b = a, the line b[0] = 1 leaves a[0] unchanged. » What does a[0] hold after these lines?
  • c) « for x in a: x = 2 * x doubles every element of a. » With a = [3, 4], what does a[0] hold after this loop?
  • d) « for i in range(1, len(a) + 1): print(a[i]) prints every element of an array of 6 elements. » How many values does it print before it stops?
  • e) « After a = [2] * 4 and a[1] = a[0] + a[3], the array a holds 2, 4, 2, 2. » What does a[1] hold?

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

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

Answers

  • a) False: the last index is 4
  • b) False: a[0] = 1
  • c) False: a[0] = 3, the array is unchanged
  • d) False: 5 values, then an IndexError
  • e) True: a[1] = 4
a)

False. [0] * 5 has 5 cells, indices 0 to 4: the last index is len(a) - 1 = 4, and a[5] would stop the program.

Correct statement: « a = [0] * 5 creates an array of 5 cells whose last index is 4. »

b)

False. b = a gives the array a second name, so b[0] = 1 changes the one array: a[0] = 1, and a = [1, 8].

Correct statement: « After b = a, a change of b[0] is seen through a; a copy needs new cells. »

c)

False. x receives a copy of each value: x = 6, then x = 8, and no cell changes. a stays [3, 4], so a[0] = 3.

Correct statement: « for i in range(len(a)): a[i] = 2 * a[i] doubles every element of a. »

d)

False. range(1, 7) gives 1 to 6: a[0] is skipped, a[1] to a[5] are printed, 5 values, and a[6] stops the program with an IndexError.

Correct statement: « for i in range(len(a)): print(a[i]) prints the 6 elements, from a[0] to a[5]. »

e)

True. [2] * 4 = [2, 2, 2, 2], then a[1] = a[0] + a[3] = 2 + 2 = 4: a = [2, 4, 2, 2].

Only cell 1 is assigned; the three others keep their 2.

Exercise 9: A thermostat schedule copied by weekend = weekday: the weekdays change too

11 answers to check

A programmable thermostat stores each schedule as an array of four set points in degrees Celsius, one per period of the day: wake, away, home and sleep. The owner wants the weekend schedule to start as a copy of the weekday one, then to keep the heat at 21 °C during the day on weekends.

Python
weekday = [21, 16, 21, 18]    # line 1
weekend = weekday             # line 2
weekend[1] = 21               # line 3
print(weekday)                # line 4
print(weekend)                # line 5
  • a) What does line 4 print? What is weekday[1] now?
  • b) How many arrays does the program hold after line 2? On weekdays, by how many degrees is the away set point now above the one the owner wanted?
  • c) Rewrite line 2 so that weekend is a separate copy, with a loop rather than the slice weekday[:]. With your fix, what do weekday[1] and weekend[1] hold after line 3?
  • d) With the fix of part c), the owner adds holiday = weekend, then holiday[3] = 19. Which schedules now have 19 at index 3? What does weekday[3] hold?
  • e) For the winter, the owner lowers every weekday set point by 1 degree with for t in weekday: t = t - 1. What is weekday[0] after this loop? With the loop for i in range(len(weekday)): weekday[i] = weekday[i] - 1 instead, what are weekday[0] and weekend[0]?

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

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

Answers

  • a) [21, 21, 21, 18]; weekday[1] = 21
  • b) 1 array with two names; 5 °C too high
  • c) weekend = [0] * len(weekday), then a loop that copies each cell; weekday[1] = 16, weekend[1] = 21
  • d) weekend and holiday; weekday[3] = 18
  • e) weekday[0] = 21, unchanged; with the index loop, weekday[0] = 20 and weekend[0] = 21

The diagram below shows the memory with line 2 as written, then with the copy of part c), whose full program is above.

a)

Line 2 gives the weekday array a second name, weekend. Line 3 changes cell 1 of that one array, so line 4 prints [21, 21, 21, 18], and weekday[1] = 21.

b)

One array, two names. On weekdays, the away set point is now 21 °C instead of 16 °C: 21 - 16 = 5 °C above what the owner wanted, for the whole time the home is empty.

Pitfall: reading weekend = weekday as a copy. The program runs without any error, and the mistake shows up on the weekday schedule, which no line of the program meant to change.

c)

New cells first, then one copy per index: weekend = [0] * len(weekday), then for i in range(len(weekday)): weekend[i] = weekday[i].

Line 3 now changes the second array only: weekday[1] = 16 and weekend[1] = 21. Line 4 prints [21, 16, 21, 18] and line 5 prints [21, 21, 21, 18].

d)

holiday = weekend gives the weekend array a second name: holiday[3] = 19 changes it, so weekend and holiday both have 19 at index 3.

weekday is a separate array since the fix of part c): weekday[3] = 18.

e)

for t in weekday: t = t - 1 changes t, a copy of each set point, never a cell: weekday[0] stays 21.

The loop over the indices changes the cells: weekday = [20, 15, 20, 17], so weekday[0] = 20. weekend is a separate array, so weekend[0] stays 21.

Python
weekday = [21, 16, 21, 18]
weekend = [0] * len(weekday)
for i in range(len(weekday)):
    weekend[i] = weekday[i]
weekend[1] = 21
print(weekday)
print(weekend)
210211212183weekdayweekend210161212183210211212183weekdayweekendweekend = weekday: one arrayWith the copy loop: two arrays

Exercise 10: Free spaces in a parking garage: level numbers from 1, indices from 0

12 answers to check

A parking garage has five levels, numbered 1 to 5 on its signs. The array free holds the number of free spaces: free[0] is level 1, free[1] is level 2, and so on. Each time a car parks or leaves, a sensor sends two whole numbers: the level, as written on the signs, and the change, -1 when a car parks and 1 when a car leaves. The program below applies n such events; the events of part b) are in the table.

Event123456
level252153
change-1-1-11-11
Python
free = [40, 32, 32, 28, 20]                     # line 1
n = int(input('Events: '))                      # line 2
for k in range(n):                              # line 3
    level = int(input('Level: '))               # line 4
    change = int(input('Change: '))             # line 5
    free[level - 1] = free[level - 1] + change  # line 6
print(free)                                     # line 7
  • a) At which index is level 4 stored? Which level numbers are valid on the signs, and which indices are valid in free?
  • b) The program receives the six events of the table. What do free[1] and free[4] hold at the end?
  • c) A first version of line 6 was free[level] = free[level] + change. With the same events, which level on the signs does the first event change? What happens at the second event?
  • d) A faulty sensor sends level 0 with change -1. With line 6 as written, which level on the signs loses a space? Does Python show an error?
  • e) Write a guard so that an event whose level is not on the signs is ignored, with the message Ignored: level, followed by the level. From line 1, the events are level 2 change -1, level 0 change -1, level 6 change 1, level 4 change -1. How many events are ignored? What do free[3] and free[4] hold at the end?

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

a)
Valid levels ,
Valid indices ,
b)
c)
d)
e)
Show the solution

Answers

  • a) Index 3; levels 1 to 5; indices 0 to 4
  • b) free[1] = 30, free[4] = 18
  • c) Level 3; at the second event, an IndexError stops the program
  • d) Level 5, and Python shows no error
  • e) 2 events ignored; free[3] = 27, free[4] = 20

Level numbers start at 1 and indices at 0: the level sent is turned into an index once, by level - 1, in the line that reaches the cell. The table below gives the cell reached for each level a sensor can send, and the program above is the guarded version of part e).

a)

Level k is at index k - 1: level 4 is free[3].

The signs go from 1 to 5, and the indices of an array of 5 cells from 0 to 4.

b)

Event 1, level 2: free[1] = 32 - 1 = 31. Event 2, level 5: free[4] = 20 - 1 = 19. Event 3, level 2: free[1] = 30. Event 4, level 1: free[0] = 41. Event 5, level 5: free[4] = 18. Event 6, level 3: free[2] = 33.

Line 7 prints [41, 30, 33, 28, 18]: free[1] = 30 and free[4] = 18.

c)

free[level] uses the sign number as an index. The first event, level 2, changes free[2], which is level 3: level 3 loses a space and level 2 keeps its count.

The second event, level 5, reads free[5], a sixth cell in an array of 5: the program stops with an IndexError.

Pitfall: a number that starts at 1 used as an index. Every level is off by one, and only the top level makes the mistake visible.

d)

0 - 1 = -1, and free[-1] is the last cell in Python, free[4]: level 5 loses a space, and no error is shown.

In Java, free[-1] stops the program with an ArrayIndexOutOfBoundsException: the same mistake stops a Java program and goes unnoticed in Python.

e)

The guard tests the level before it is used as an index: if level >= 1 and level <= len(free): applies the change, else prints Ignored: level and the level.

Level 2 change -1: free[1] = 31. Level 0: ignored. Level 6: ignored. Level 4 change -1: free[3] = 28 - 1 = 27.

2 events are ignored; free[3] = 27, and free[4] keeps 20 since the level 0 event is no longer applied.

Testing the two levels just outside the signs, 0 and 6, is what shows the guard works: one goes through a negative index, the other past the end.

Python
free = [40, 32, 32, 28, 20]
n = int(input('Events: '))
for k in range(n):
    level = int(input('Level: '))
    change = int(input('Change: '))
    if level >= 1 and level <= len(free):
        free[level - 1] = free[level - 1] + change
    else:
        print('Ignored: level', level)
print(free)
level sentlevel - 1cell reached0-1free[-1], that is free[4]: level 510free[0]: level 121free[1]: level 232free[2]: level 343free[3]: level 454free[4]: level 565no cell: IndexErrorfree[level - 1]: the cell reached for each level sent
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-one-dimensional-arrays. 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: arrays come back in every later unit of the course, from algorithms to subprograms.

Site by Studio Squalli