ICS3U practice final exam with full solutions (Ontario Grade 11 Computer Science)
ICS3U practice final exam (Ontario Grade 11 Computer Science)
Name: Class: Date:
Solutions
Suggested time: 2 h 00 · No calculator · 10 exercises https://www.letuteurscientifique.ca/en/exercices/ics3u-practice-final-exam
This practice final examination covers ICS3U, Introduction to Computer Science, Grade 11, University Preparation, in Ontario: its strands on programming concepts and skills, software development, and computer environments and systems, with one question for each chapter set of the course, one-dimensional arrays and array algorithms sharing question 5.
What the set covers, the traps it targets
Ten questions, 100 marks, two hours, no calculator and no computer. The code is in Python 3; tracing, testing and designing an algorithm work the same way in any language. Each question is labelled with its category of the achievement chart of the Ontario curriculum and with its marks: Part A, Knowledge and Understanding (30 marks), data types and expressions around a podcast timer (question 1), binary, hexadecimal and ASCII (question 2), and the components, software, malware and backups of a computer (question 3); Part B, Application (30 marks), the postal code of a shipping label (question 4), the results of a cross-country race in parallel arrays, with a linear search, an insertion and a deletion (question 5), and a paint calculator built from functions (question 6); Part C, Thinking (25 marks), the Do Not Disturb mode of a phone (question 7), the levels of a video game (question 8) and the test plan of a class trip program (question 9); Part D, Communication (15 marks), the specification, design and schedule of a volleyball league app (question 10).
Sit it in one session: two hours on a timer, a pen, no notes, and every program traced by hand. Write each step as on paper, since the marks go to the trace, the reason and the sentence that answers the question. Then mark your work with the Answers box of each question, read the full solution, and list the questions where you lost marks: each one points to the chapter set to redo. In Ontario, the final evaluation of a course counts for 30 % of the final grade, and the curriculum lets it be an examination, a performance such as a programming project, or another form: this paper practises the written part only, and it does not reproduce any school's examination. No question repeats an exercise of the eleven chapter sets of the course: the skills are the same, the situations and the numbers are new.
The traps of the chapters come back, each named in a solution: -6 ** 2 read as (-6) ** 2 and the string that input() gives back (question 1), the binary weights read from the wrong side (question 2), RAM taken for storage (question 3), a string method whose result is not stored and code[0] == "K" or "L" (question 4), a minimum that starts at 0 and an insertion that shifts from the right (question 5), print instead of return and a local variable that hides a global one (question 6), and instead of or across midnight and the negation of a compound condition (question 7), a loop that ends because another variable of its condition changes (question 8), a boundary excluded by < and an expected outcome computed by hand (question 9), and the critical path, which is the longest path (question 10).
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.
•Python 3: / gives a float, // and % give the quotient and the remainder of two positive whole numbers.
•A program line referred to by a question ends with a comment # line n.
•An array is a Python list, indexed from 0 to len(a) - 1; size counts the cells in use of a partially filled array.
•A test plan: input, expected outcome computed from the specification, actual outcome, pass or fail.
•Marks per category: Knowledge and Understanding 30, Application 30, Thinking 25, Communication 15.
Part A: Knowledge and Understanding (/30)
Exercise 1: Knowledge and Understanding: data types, expressions and assignment
17 answers to check
Knowledge and Understanding, 10 marks, two per part. Give the value that Python 3 computes. A value that print shows with a decimal point, such as 8.0, is a float: type 8 in the field.
Parts d) and e) use the program below, written to show the length of a podcast episode in minutes and seconds.
Python
total = input("Length in seconds: ") # line 1
minutes = total // 60 # line 2
seconds = total % 60 # line 3
print(minutes, "min", seconds, "s") # line 4
a) Give the value of each expression: 4 + 6 / 3 * 2 • 3 ** 1 ** 2 • -6 ** 2 + 40 • (14 - 2) % 5 • 38 // 7 * 7 + 38 % 7
b) Give the type of each value: 4 + 6 / 3 * 2 • '15' + '8' • 9 > 4.5 • 38 // 7
c) Four assignments run in this order: a = 3, then b = a + 4, then a = b * a, then b = a - b. Give the final values of a and b.
d) The user types 754. What happens at line 2? Once line 1 reads total = int(input("Length in seconds: ")), what does line 4 print?
e) Lines 2 and 3 use the number 60 twice. Which name follows the professional convention for this constant? With lines 2 and 3 rewritten to use it, what does the program print for 3600 seconds?
Show the solution
Answers
a)8.0 (type 8), 3, 4, 2 and 38
b)float, str, bool, int
c)a = 21 and b = 14
d)TypeError at line 2, since total is the string '754'; with int(), 12 min 34 s
e)SECONDS_PER_MINUTE; 60 min 0 s
a)
Python applies the brackets first, then **, grouped from right to left and applied before a minus sign written in front, then *, /, // and % from left to right, then + and -.
4 + 6 / 3 * 2: 6 / 3 = 2.0, then 2.0 * 2 = 4.0, then 4 + 4.0 = 8.0. / gives a float, and the result stays a float.
3 ** 1 ** 2: the ** on the right comes first, 1 ** 2 = 1, then 3 ** 1 = 3. Grouped from the left, (3 ** 1) ** 2 would give 9.
-6 ** 2 + 40: ** runs before the minus sign, so -6 ** 2 is -(6 ** 2) = -36, and -36 + 40 = 4.
(14 - 2) % 5: 12 % 5 = 2, the remainder of 12 divided by 5.
38 // 7 * 7 + 38 % 7: 38 // 7 = 5, then 5 * 7 = 35, and 38 % 7 = 3, so 35 + 3 = 38: the quotient times the divisor plus the remainder gives back the number.
b)
4 + 6 / 3 * 2 is a float, since / gives a float in Python 3 (8.0).
'15' + '8' joins two strings: '158', a str.
9 > 4.5 is a comparison: its value is True, a bool.
38 // 7 divides two int values and keeps the whole part: 5, an int.
In Java, / between two int values gives an int: 38 / 7 is 5 in Java, about 5.43 in Python.
c)
Each assignment computes its right side with the values of that moment, then replaces the value on its left:
a = 3: a holds 3.
b = a + 4: b holds 7.
a = b * a: 7 * 3 = 21, so a holds 21; b still holds 7.
b = a - b: 21 - 7 = 14, so b holds 14.
Final values: a = 21 and b = 14.
Pitfall: = is not an equation. After a = b * a, the old value 3 is gone, and b = a - b uses 21.
d)
input() gives back what the user typed as a string: total holds '754', not the number 754.
Line 2 asks for '754' // 60, a string divided by an int: Python stops with TypeError: unsupported operand type(s) for //: 'str' and 'int'. Lines 3 and 4 never run.
With int(input(...)), total is the int 754: minutes = 754 // 60 = 12, and seconds = 754 % 60 = 754 - 720 = 34.
Line 4 prints 12 min 34 s.
e)
A constant holds a value that does not change while the program runs. The convention writes its name in capital letters, with an underscore between the words, and the name says what the value means: SECONDS_PER_MINUTE = 60, assigned once at the top of the program.
x says nothing; sixty names the value, not its meaning; Seconds per minute has spaces, so it is not a valid name.
Lines 2 and 3 become minutes = total // SECONDS_PER_MINUTE and seconds = total % SECONDS_PER_MINUTE (solution code).
For 3600 seconds: 3600 // 60 = 60 and 3600 % 60 = 0. The program prints 60 min 0 s.
Python
SECONDS_PER_MINUTE = 60
total = int(input("Length in seconds: "))
minutes = total // SECONDS_PER_MINUTE
seconds = total % SECONDS_PER_MINUTE
print(minutes, "min", seconds, "s")
Points are earned before the solution; after it, you can keep practising.
For you:
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: Knowledge and Understanding: binary, hexadecimal and ASCII
9 answers to check
Knowledge and Understanding, 10 marks, two per part. In binary, the weights are 1, 2, 4, 8, 16, ... from the right; in hexadecimal, they are 1, 16, 256, ..., with the digits A to F for 10 to 15. A byte is 8 bits.
a) Convert the binary number 10110101 to decimal.
b) Convert the decimal number 172 to binary, on 8 bits, and to hexadecimal.
c) Convert the hexadecimal number 9E to decimal, then to binary on 8 bits.
d) A concert hall numbers its 2000 seats from 1 to 2000, and its ticket system stores each seat number in binary. How many bits does it need, at least? Why are 10 bits too few?
e) A grayscale photo of 40 by 30 pixels stores each pixel in one byte, from 0 (black) to 255 (white). How many bytes do its pixels take? The year 2026 is stored as the text '2026' in ASCII, one byte per character: how many bits does it take? How many bits does the binary form of the whole number 2026 need, at least?
Show the solution
Answers
a)181
b)10101100 in binary, AC in hexadecimal
c)158, that is 10011110 in binary
d)11 bits; 10 bits stop at 1023
e)1200 bytes; 32 bits for the text '2026'; 11 bits for the binary form of 2026
a)
Write the weights under the bits, from the right: 128, 64, 32, 16, 8, 4, 2, 1.
10110101 has its 1s at the weights 128, 32, 16, 4 and 1.
128 + 32 + 16 + 4 + 1 = 181.
Pitfall: giving the weight 1 to the leftmost bit reads the number backwards, 10101101, which is 173.
b)
Repeated division by 2; the remainders, read from the last one up, are the bits:
Read from the bottom: 10101100. Check: 128 + 32 + 8 + 4 = 172.
Hexadecimal: cut the 8 bits into two groups of four, 1010 and 1100. 1010 is 10, the digit A, and 1100 is 12, the digit C: 172 is AC. Check: 10 × 16 + 12 = 172.
Pitfall: writing 1012 for 10 and 12. One hexadecimal digit stands for one group of four bits, from 0 to F.
c)
E is 14: 9 × 16 + 14 = 144 + 14 = 158.
Each hexadecimal digit becomes four bits: 9 is 1001 and E is 1110, so 9E is 10011110.
Check: 128 + 16 + 8 + 4 + 2 = 158.
d)
n bits give 2 ** n different values. 2 ** 10 = 1024 values are fewer than 2000 seats, and 2 ** 11 = 2048 values are enough: 11 bits.
With 10 bits, the largest number is 1023, so the seats 1024 to 2000 would have no code.
e)
The photo has 40 × 30 = 1200 pixels, one byte each: 1200 bytes. Each pixel is a number, its brightness.
The text '2026' has 4 characters, one byte each in ASCII: 4 bytes, that is 4 × 8 = 32 bits. The character '2' is stored as its ASCII code, 50, not as the number 2.
The number 2026 lies between 2 ** 10 = 1024 and 2 ** 11 = 2048: its binary form, 11111101010, needs 11 bits.
Pitfall: a number typed as text takes one byte per digit; written in binary, the same number 2026 needs 11 bits.
Points are earned before the solution; after it, you can keep practising.
For you:
Exercise 3: Knowledge and Understanding: components, software, malware and backups
16 answers to check
Knowledge and Understanding, 10 marks, two per part. Choose the answer of each field; the solution gives the reason.
a) The corrected program of question 1 is saved as podcast.py on the SSD of a laptop, and it runs. Which component does each job: it computes total // 60; it holds the value of minutes while the program runs; it keeps podcast.py when the laptop is off; it holds the start-up instructions that run before the operating system is loaded?
b) A laptop has 8 GB of RAM and a 256 GB SSD with 3 GB free. Saving a 5 GB video fails with the message « Disk full ». A friend says: « Add 8 GB of RAM. » Would that let the video be saved? How many GB must be freed on the SSD, at least?
c) Is each one an application, a programming language or an operating system: Linux; Python; a spreadsheet program? Then, is each translator a compiler or an interpreter:1)it turns the whole source file, once, into a machine-code file that then runs without it2)it translates and runs the program as it goes, every time the program is run?
d) Name each malware:1)it records every key typed and sends the text to a stranger2)it copies itself from computer to computer over a network, with no host file and no user action3)a free photo-filter app that works as promised, but also opens a way into the phone for a stranger.
e) A small animation studio makes a full backup of its project folder on Saturday at 23:00 (60 GB), then an incremental backup each night at 23:00: 3 GB on Sunday, 5 GB on Monday, 2 GB on Tuesday. The SSD fails on Wednesday at noon. How many backups must be read to restore the folder as it was on Tuesday at 23:00? How many GB do these backups take? Which work is lost?
e)4 backups (the full one, then Sunday, Monday, Tuesday); 70 GB; the work done after Tuesday 23:00 is lost
a)
The CPU (processor) carries out the instructions, the arithmetic included: it computes total // 60.
The RAM holds the running program and its variables, minutes among them; it loses them when the power goes off.
The SSD keeps files without power: podcast.py stays there when the laptop is off.
The ROM holds the firmware, the start-up instructions, which run before the operating system is loaded from the SSD into RAM.
b)
« Disk full » is about storage: the video needs 5 GB, and the SSD has 3 GB free.
RAM is working memory: more RAM lets more programs and data be open at once, but it adds no space to save a file. The friend's fix does not work.
5 - 3 = 2 GB must be freed on the SSD, at least, or the video saved on another drive.
Pitfall: RAM and storage are both counted in GB, but RAM is emptied at power off, while storage keeps a file.
c)
Linux is an operating system: it manages the computer for all the programs, its memory, its files and its devices. Python is a programming language: words and rules to write instructions. A spreadsheet program is an application: it does a task for its user.
1) Translating the whole source once into a machine-code file that runs on its own is the work of a compiler.
2) Translating and running as it goes, each time the program runs, is the work of an interpreter: it is how Python programs are usually run, in the model of the course.
d)
1) Software that spies on the user and sends what it records is spyware.
2) A program that spreads by itself over a network is a worm; a virus needs a host file that someone opens.
3) A program that does what it promises while hiding a harmful part is a Trojan horse; it does not copy itself.
e)
An incremental backup saves only what changed since the previous backup. To get back to Tuesday 23:00, restore the full backup of Saturday, then the incrementals of Sunday, Monday and Tuesday, in that order: 4 backups.
Space: 60 + 3 + 5 + 2 = 70 GB.
The changes made after the last backup, from Tuesday 23:00 to the failure on Wednesday at noon, were never saved: that work is lost.
Pitfall: restoring only the last incremental gives back Tuesday's changes, not the folder; each incremental needs the full backup and the incrementals before it.
Points are earned before the solution; after it, you can keep practising.
For you:
Part B: Application (/30)
Exercise 4: Application: the postal code of a shipping label
11 answers to check
Application, 10 marks, two per part. A shipping app prints labels. A Canadian postal code has seven characters: a letter, a digit, a letter, a space, then a digit, a letter, a digit, as in K7M 4X2. Its first three characters, the forward sortation area (FSA), name a region; the last three, the local delivery unit (LDU), a smaller area. The program below cleans a code typed by a clerk, with two spaces before it and one after it, then checks it.
Python
raw = " k7m 4x2 " # line 1
code = raw.strip().upper() # line 2
fsa = code[0:3] # line 3
ldu = code[4:] # line 4
print(fsa, ldu, len(code)) # line 5
letters = 0 # line 6
digits = 0 # line 7
for ch in code: # line 8
if ch.isalpha(): # line 9
letters = letters + 1 # line 10
elif ch.isdigit(): # line 11
digits = digits + 1 # line 12
ok = len(code) == 7 and code[3] == " " # line 13
ok = ok and letters == 3 and digits == 3 # line 14
print(ok) # line 15
a) What does line 5 print? How many characters does raw hold?
b) A student replaces line 2 by three lines: raw.strip(), then raw.upper(), then code = raw. What do len(code) and fsa hold now? Explain.
c) Line 1 is replaced in turn by each of these four codes, with no spaces around them: 7KM 4X2; K7M4X2; K7M-4X2; k7m 4x2. For how many of them does line 15 print True? Which one is accepted although it is not a valid postal code?
d) To print a label line, a student adds label = "Region " + fsa + ", " + len(code) + " characters". What happens? Correct the line.
e) The first letter tells the province: K, L, M, N and P are the letters of Ontario. A student adds the test if code[0] == "K" or "L" or "M" or "N" or "P": to print Ontario, with else: to print Outside Ontario. What does it print for R2W 5J3, a code of Manitoba? Which condition is correct?
Show the solution
Answers
a)K7M 4X2 7; raw holds 10 characters
b)len(code) is 10 and fsa is two spaces followed by k: strip() and upper() did not change raw
c)2 codes are accepted, 7KM 4X2 among them, wrongly
d)TypeError: a str and an int cannot be joined by +; str(len(code)) gives Region K7M, 7 characters
e)It prints Ontario, as for every code; the correct condition is code[0] in "KLMNP"
a)
Line 2: strip() gives back a copy without the spaces at both ends, k7m 4x2, then upper() a copy in capital letters: code is K7M 4X2, 7 characters.
Line 3: code[0:3] takes the indices 0, 1 and 2, the end index 3 being excluded: K7M.
Line 4: code[4:] takes the characters from index 4 to the end: 4X2. Index 3 is the space, which neither slice takes.
Line 5 prints K7M 4X2 7.
raw holds 2 spaces, 7 characters and 1 space: len(raw) is 10, and line 2 does not change raw.
b)
A string never changes. raw.strip() and raw.upper() each build a new string and give it back; written alone on a line, the new string is stored nowhere, and raw keeps its 10 characters.
code = raw then names the same text: len(code) is 10, and fsa = code[0:3] is two spaces followed by k.
Pitfall: a string method gives back a new string; store it, as in raw = raw.strip(), or chain the calls as line 2 does.
c)
Lines 6 to 14 count the letters and the digits and check the length and the space at index 3, but never where each letter and each digit stands.
7KM 4X2: 7 characters, a space at index 3, 3 letters (K, M, X) and 3 digits (7, 4, 2): True.
K7M4X2: 6 characters, False. K7M-4X2: index 3 holds a dash, False. k7m 4x2: line 2 makes it K7M 4X2, True.
2 of the 4 codes are accepted, and 7KM 4X2 is accepted although its first character is a digit.
A check that accepts the valid codes is not yet a correct check: it must also refuse the wrong ones. The corrected check tests each position, isalpha() at the indices 0, 2 and 5 and isdigit() at the indices 1, 4 and 6 (solution code).
d)
+ joins two strings, but len(code) is the int 7: Python stops with TypeError: can only concatenate str (not "int") to str.
str() turns the number into text: label = "Region " + fsa + ", " + str(len(code)) + " characters" builds Region K7M, 7 characters.
e)
Python reads the condition as (code[0] == "K") or "L" or "M" or "N" or "P". For R2W 5J3, code[0] == "K" is False, so or moves on to "L", a string that is not empty, which counts as true: the if branch runs, and the program prints Ontario, for this code as for every other.
code[0] in "KLMNP" is True when the first character is one of the five letters: for R2W 5J3 it is False, and the program prints Outside Ontario. The long form also works, with one comparison per letter: code[0] == "K" or code[0] == "L" or code[0] == "M", and so on.
code[0] == "KLMNP" compares one character with a string of five: False for every code. code in "KLMNP" looks for the whole code inside KLMNP: False for every valid code.
Pitfall: or joins two conditions; it does not share the comparison == with the values written after it.
Python
code = input("Postal code: ").strip().upper()
ok = len(code) == 7 and code[3] == " "
# when ok is False, and stops at once: code[5] is never read on a short code
ok = ok and code[0].isalpha() and code[2].isalpha() and code[5].isalpha()
ok = ok and code[1].isdigit() and code[4].isdigit() and code[6].isdigit()
if not ok:
print("Not a valid postal code")
elif code[0] in "KLMNP":
print("Ontario")
else:
print("Outside Ontario")
Points are earned before the solution; after it, you can keep practising.
For you:
Exercise 5: Application: the results of a cross-country race in arrays
15 answers to check
Application, 10 marks, two per part. A school cross-country race is timed in seconds. Two parallel one-dimensional arrays, lists in Python, hold the runners in the order of their bib numbers: names[i] is a runner and times[i] that runner's time (figure). The results board keeps the times sorted, from the fastest, in an array with two spare cells at the end; size counts the cells in use.
The program below is cut into five parts; each part of the question runs its own part, after the first two lines. In the answers, max(), min(), sum(), in, index(), insert() and pop() are not used: each algorithm is a loop.
Python
names = ["Omar", "Lucia", "Jonah", "Sana", "Theo", "Mei"]
times = [1187, 1131, 1203, 1104, 1162, 1150]
# Part a: count
count = 0
for i in range(len(times)):
if times[i] < 1160:
count = count + 1
print(count)
# Part b: the winner, a student's version
fastest = 0
where = 0
for i in range(len(times)):
if times[i] < fastest:
fastest = times[i]
where = i
print(fastest, names[where])
# Part c: linear search
target = input("Name: ")
pos = -1
i = 0
while i < len(names) and pos == -1:
if names[i] == target:
pos = i
i = i + 1
print(pos)
# Part d: insertion into the sorted board
board = [1104, 1131, 1150, 1162, 1187, 1203, 0, 0]
size = 6
value = 1158
i = size - 1
while i >= 0 and board[i] > value:
board[i + 1] = board[i]
i = i - 1
board[i + 1] = value
size = size + 1
# Part e: deletion at index 1, after part d
for k in range(1, size - 1):
board[k] = board[k + 1]
size = size - 1
a) What does part a print? What is the index of the last runner it counts?
b) What does the student's part b print? Which first values make it correct, and what does it print then?
c) In part c, a comparison is one test names[i] == target. Give pos and the number of comparisons when the user types Theo, then when the user types Maya, who did not run.
d) Part d inserts a late entry, 1158, by shifting from the right. At which index does 1158 land? How many cells move? What is size after?
e) Lucia, whose time 1131 sits at index 1 of the board, is disqualified, and part e runs after part d. Give board[1] and board[5] after the loop. If the last line, size = size - 1, is forgotten, how many times does 1203 appear among the first size cells?
Show the solution
Answers
a)3; the last runner counted is at index 5 (Mei)
b)0 Omar; with fastest = times[0] and where = 0, it prints 1104 Sana
c)Theo: pos 4 after 5 comparisons; Maya: pos -1 after 6 comparisons
d)index 3; 3 cells move; size 7
e)board[1] = 1150 and board[5] = 1203; without size - 1, 1203 appears 2 times
a)
The loop visits the indices 0 to 5 and adds 1 to count when the time is under 1160:
1187 no, 1131 yes, 1203 no, 1104 yes, 1162 no, 1150 yes.
Part a prints 3. The last runner counted is at index 5, Mei, with 1150 s.
b)
fastest starts at 0, and no time is below 0: the test times[i] < fastest is False on every pass, nothing changes, and the program prints 0 Omar, a time nobody ran and the runner at index 0.
Pitfall: a starting value that is not a value of the array can win against all of them. Start from the first element, fastest = times[0] and where = 0, then compare the others (solution code).
Corrected: 1187, then 1131 (index 1), then 1104 (index 3); 1162 and 1150 are not smaller. It prints 1104 Sana.
c)
The loop compares names[0], names[1], and so on, and stops as soon as pos is no longer -1.
Theo: Omar, Lucia, Jonah, Sana, then Theo matches at index 4. pos is 4, after 5 comparisons.
Maya: the six names are compared, none matches, and i reaches 6 = len(names): pos is -1 after 6 comparisons. -1 is not an index of the array, so it cannot be mistaken for a position.
In Java, two strings are compared with equals(), not with ==: names[i].equals(target).
d)
i starts at size - 1 = 5. While the cell holds a time greater than 1158, it is copied one cell to the right:
i = 5: 1203 > 1158, board[6] = 1203. i = 4: 1187 > 1158, board[5] = 1187. i = 3: 1162 > 1158, board[4] = 1162. i = 2: 1150 > 1158 is False, the loop ends.
size becomes 6: the board is 1104, 1150, 1158, 1162, 1187, 1203, and cell 6 is spare again.
Without size = size - 1, size stays 7, and the first 7 cells hold 1203 at index 5 and at index 6: 2 times.
Python
fastest = times[0]
where = 0
for i in range(1, len(times)):
if times[i] < fastest:
fastest = times[i]
where = i
print(fastest, names[where])
Points are earned before the solution; after it, you can keep practising.
For you:
Exercise 6: Application: a paint calculator built from functions
10 answers to check
Application, 10 marks, two per part. A hardware store's app estimates the paint for a room. The four walls of a room of length L and width W, in metres, with a ceiling at height H, have an area of 2 × (L + W) × H square metres, doors and windows ignored. One can covers 10 square metres with one coat. math.ceil(x), from the module math, gives back the smallest whole number at least equal to x: math.ceil(2.1) is 3.
Python
import math # line 1
COVERAGE = 10 # square metres per can, for one coat # line 2
def wall_area(length, width, height): # line 3
return 2 * (length + width) * height # line 4
def cans_needed(area, coats): # line 5
return math.ceil(area * coats / COVERAGE) # line 6
room = wall_area(4, 3, 2.5) # line 7
print(room, cans_needed(room, 2)) # line 8
def total_cans(areas, coats): # line 9
total = 0 # line 10
for i in range(len(areas)): # line 11
... # line 12
return total # line 13
a) What does line 8 print?
b) For walls of 32 square metres and one coat, what do round(32 * 1 / 10) and math.ceil(32 * 1 / 10) give? Explain why line 6 uses math.ceil.
c) A student writes line 6 as print(math.ceil(area * coats / COVERAGE)), with no return, then runs total = cans_needed(35, 2) + cans_needed(12, 2). What does cans_needed(35, 2) give back? What happens on that line?
d) For a premium paint that covers 12 square metres per can, a student adds a function premium whose body is the single line COVERAGE = 12, calls premium(), then prints cans_needed(35, 2). What is printed? What is printed if the body of premium starts with the line global COVERAGE?
e) total_cans gives back the number of cans for several rooms with the same number of coats; each room has its own colour, so its cans are counted separately. Which line is missing at line 12? What does total_cans([35.0, 22.5, 12.0], 2) give back?
Show the solution
Answers
a)35.0 7
b)round gives 3 and math.ceil gives 4: a can is bought whole, so the count is rounded up
c)None; it prints 7 and 3, then stops with TypeError
d)7, since COVERAGE = 12 creates a local variable; with global COVERAGE, 6
e)total = total + cans_needed(areas[i], coats); 15 cans
a)
Line 7 calls wall_area with length = 4, width = 3 and height = 2.5, matched by position: 2 * (4 + 3) * 2.5 = 2 * 7 * 2.5 = 35.0, a float since 2.5 is one.
Three cans cover 30 square metres, and 2 square metres of wall would stay bare. A can is bought whole, so any part of a can counts as one more can: the count is rounded up, which is what math.ceil does.
c)
A function with no return statement gives back None, the value that stands for no value.
cans_needed(35, 2) prints 7 and gives back None; cans_needed(12, 2) prints 3 (24 / 10 = 2.4, rounded up) and gives back None.
Then None + None: Python stops with TypeError: unsupported operand type(s) for +: 'NoneType' and 'NoneType', and total is never assigned.
Pitfall: print shows a value to the user; return gives it back to the program. A function whose result is used in a calculation must return it.
d)
An assignment inside a function creates a local variable, unless the name is declared global. premium() creates a local COVERAGE that holds 12 and disappears when the call ends; the global COVERAGE still holds 10, and line 6 reads it: 35 * 2 / 10 = 7.0, and 7 is printed.
With global COVERAGE as the first line of premium, the assignment changes the global variable: 35 * 2 / 12 = 70 / 12, about 5.83, rounded up to 6, and 6 is printed.
A third parameter, cans_needed(area, coats, coverage), would let each call give its own coverage without changing a global variable.
e)
The loop must add the cans of each room to total: line 12 is total = total + cans_needed(areas[i], coats). It calls the function already written instead of copying its formula, which is the point of a subprogram.
35.0 * 2 / 10 = 7.0, so 7 cans; 22.5 * 2 / 10 = 4.5, so 5 cans; 12.0 * 2 / 10 = 2.4, so 3 cans.
total_cans gives back 7 + 5 + 3 = 15.
The other lines: total = cans_needed(areas[i], coats) keeps the last room only, 3; a return inside the loop gives back the first room, 7, after one pass; total = total + areas[i] adds square metres, 69.5, not cans.
Points are earned before the solution; after it, you can keep practising.
For you:
Part C: Thinking (/25)
Exercise 7: Thinking: the Do Not Disturb mode of a phone
11 answers to check
Thinking, 8 marks (2 + 2 + 2 + 1 + 1). A phone's Do Not Disturb mode keeps it silent during quiet hours, from 22:00 to 7:00 the next morning. During quiet hours, a call still rings if the caller is a favourite contact, or if the same caller already called in the last 3 minutes, 3 minutes included. The hour is a whole number from 0 to 23: 22 stands for 22:00 to 22:59. The minutes are a whole number.
Python
hour = int(input("Hour (0 to 23): ")) # line 1
favourite = input("Favourite contact? (y/n): ") == "y" # line 2
minutes = int(input("Minutes since this caller's last call: ")) # line 3
quiet = hour >= 22 or hour < 7 # line 4
if not quiet: # line 5
print("Ring") # line 6
elif favourite: # line 7
print("Ring: favourite") # line 8
elif minutes <= 3: # line 9
print("Ring: repeated call") # line 10
else: # line 11
print("Silent") # line 12
a) Give the value of quiet, on line 4, for hour = 22, for hour = 7 and for hour = 0.
b) A student first wrote line 4 as quiet = hour >= 22 and hour < 7. For how many of the 24 hours does it give a wrong value? Explain why.
c) What does the program print for each call:1)hour 23, not a favourite, last call 10 minutes ago2)hour 6, a favourite, 30 minutes3)hour 21, not a favourite, 1 minute4)hour 2, not a favourite, 3 minutes?
d) A tester needs one condition that is True when the phone prints Silent and False otherwise. Which one is it?
e) At hour 1, for a caller who is not a favourite, give the whole numbers of minutes for which the phone rings, as an interval. If line 9 is written minutes < 3, which value of minutes gets a different output?
Show the solution
Answers
a)True for 22, False for 7, True for 0
b)9 hours wrong (22, 23 and 0 to 6): no hour is both at least 22 and under 7
e)[0, 3], that is 0, 1, 2 or 3 minutes; the value 3
a)
hour = 22: hour >= 22 is True, so the or is True: quiet hours.
hour = 7: 7 >= 22 is False and 7 < 7 is False: not quiet, since the quiet hours end at 7:00.
hour = 0: 0 < 7 is True: quiet.
The quiet hours cross midnight: they are the hours at the end of the day or at the start of the next one, two pieces of the scale 0 to 23.
b)
No whole number is at least 22 and under 7 at the same time: hour >= 22 and hour < 7 is False for every hour, and the phone is never quiet.
The value is wrong for the 9 quiet hours, 22 and 23, then 0 to 6 (2 + 7 = 9), and right for the 15 other hours.
Pitfall: and asks for both conditions at once. A range of hours that wraps around midnight is made of two pieces, joined by or.
c)
1) Hour 23, not a favourite, 10 minutes: quiet is True, favourite is False, 10 <= 3 is False: the else branch prints Silent.
2) Hour 6, a favourite: quiet is True and favourite is True: Ring: favourite. Line 9 is not tested.
3) Hour 21: quiet is False, so not quiet is True: Ring, whatever the other two inputs.
4) Hour 2, not a favourite, 3 minutes: quiet, not a favourite, 3 <= 3 is True: Ring: repeated call.
A cascade runs the first branch whose condition is True, and only that one: line 7 is tested only when line 5 was False, and line 9 only when lines 5 and 7 were False.
d)
Silent is printed when the three earlier conditions are all False: not quiet is False, favourite is False and minutes <= 3 is False. That is quiet and not favourite and minutes > 3.
By De Morgan's law, not (A or B or C) is (not A) and (not B) and (not C): the not of an or is the and of the nots.
Pitfall: not quiet or not favourite or minutes > 3 keeps the or. At hour 12, not quiet is True, so this condition is True while the phone rings.
e)
At hour 1 the phone is in quiet hours and the caller is not a favourite, so it rings only through line 9: minutes <= 3, that is 0, 1, 2 or 3 minutes, the whole numbers of the interval [0, 3].
With minutes < 3, a call 3 minutes after the last one goes to Silent instead of Ring: repeated call. A boundary written with < instead of <= excludes the limit value, and only a test at minutes = 3 shows it.
Points are earned before the solution; after it, you can keep practising.
For you:
Exercise 8: Thinking: the levels of a video game
10 answers to check
Thinking, 8 marks (2 + 1 + 1 + 2 + 2). In a video game, a player starts at level 1. Going from level 1 to level 2 costs 100 experience points (XP), and each level after that costs 50 XP more than the one before: 150 XP for level 3, 200 XP for level 4, and so on. The program below reads the XP a player has earned and gives the level reached and the XP left over.
Python
xp = int(input("XP earned: ")) # line 1
level = 1 # line 2
need = 100 # line 3
while xp >= need: # line 4
xp = xp - need # line 5
level = level + 1 # line 6
need = need + 50 # line 7
print(level, xp) # line 8
a) Trace the program for an input of 600, one row per pass. How many passes does the loop make, and what does line 8 print?
b) What does line 8 print for 99, and for 100? Which comparison decides between the two?
c) Without running the program, find the smallest input that reaches level 6.
d) A student types line 5 as xp - need, without xp =. Does the program still end for every input? What does it print for 600?
e) Another student computes the XP needed to go from level 1 to level 11 with total = 0, then for k in range(1, 11): and the body total = total + 100 + 50 * (k - 1). How many passes does the loop make, and what is total after it?
Show the solution
Answers
a)3 passes; 4 150
b)1 99, then 2 0; the >= of line 4
c)1000 XP
d)Yes, since need still grows; 12 600
e)10 passes; total = 3250
a)
Before the loop: xp = 600, level = 1, need = 100 (trace table in the solution figure).
Pass 1: 600 >= 100, so xp = 500, level = 2, need = 150.
Pass 2: 500 >= 150, so xp = 350, level = 3, need = 200.
Pass 3: 350 >= 200, so xp = 150, level = 4, need = 250.
Test: 150 >= 250 is False, the loop ends after 3 passes, and line 8 prints 4 150.
b)
For 99: 99 >= 100 is False at the first test: no pass, and line 8 prints 1 99.
For 100: 100 >= 100 is True: one pass, xp = 0, level 2, need 150; then 0 >= 150 is False. Line 8 prints 2 0.
The >= of line 4 decides: a player with 100 XP has paid for level 2. With >, the input 100 would stay at level 1.
c)
Reaching level 6 means paying for the levels 2 to 6: 100 + 150 + 200 + 250 + 300 = 1000 XP.
Check: for 1000, the fifth pass leaves xp = 0 at level 6. For 999, the fifth test is 299 >= 300, False, and the player stays at level 5 with 299 XP.
d)
xp - need computes a value and stores it nowhere: xp keeps 600. But line 7 still runs on every pass, and need, which the condition also reads, grows by 50 each time: the test xp >= need becomes False once need is larger than xp, so the loop ends for every input.
For 600, need takes the values 100, 150, ..., 600: 11 passes, and the test with need = 650 is False. Line 8 prints 12 600, a level the player did not earn.
A while loop ends when a variable of its condition changes in the right direction; here it is need, not xp, and the program ends with a logic error that no message reveals.
e)
The pass for k adds the cost of level k + 1: 100 + 50 * (k - 1). range(1, 11) gives k = 1 to 10: 10 passes, for the levels 2 to 11.
total = 100 + 150 + ... + 550. Pair the first and the last terms: 100 + 550 = 650, and the ten terms make 5 such pairs: 5 × 650 = 3250.
Check with the program of the question: for 3250, it prints 11 0.
Points are earned before the solution; after it, you can keep practising.
For you:
Exercise 9: Thinking: the test plan of a class trip program
14 answers to check
Thinking, 9 marks (2 + 2 + 2 + 2 + 1). A class plans a day trip to a provincial park. The bus costs 1200 dollars, shared equally by the students who go, and each student also pays 15 dollars for the park entry. Specification: the teacher types the number of students, a whole number from 1 to 60, since the bus has 60 seats; the program shows the cost per student, rounded to the cent. Any other entry, a whole number outside 1 to 60 or a text that is not a whole number, gets the message Type a whole number from 1 to 60.
The test plan below was written before the program was run.
Test
Input
Expected outcome
Actual outcome
Pass or fail
1
40
2
60
3
0
4
1
5
61
6
forty
Python
text = input("Students on the trip: ") # line 1
n = int(text) # line 2
if n > 0 and n < 60: # line 3
share = 1200 / n + 15 # line 4
print("Cost per student:", round(share, 2)) # line 5
else: # line 6
print("Type a whole number from 1 to 60") # line 7
a) Compute the expected outcome of tests 1, 2 and 4 from the specification.
b) Run the program by hand on the six tests and fill in the plan. How many tests fail, and which ones?
c) For each failing test, is the error a syntax error, a run-time error or a logic error? For the run-time error, give the type of the exception and the line that Python names.
d) A test plan of this course takes one test in each class of inputs, and tests each boundary between two classes on both sides; one test may serve several of these purposes. What is the smallest number of tests that meets this rule? Which test of the plan is not needed by the rule?
e) Which line 3 meets the specification, and where does a try go so that forty gets the message instead of a traceback?
Show the solution
Answers
a)Test 1: 45.0; test 2: 35.0; test 4: 1215.0
b)2 tests fail: tests 2 and 6
c)Test 2: logic error; test 6: run-time error, ValueError at line 2
d)5 tests (0, 1, 60, 61 and a text); test 1 is not needed
e)if 1 <= n <= 60:; a try around line 2 only, with except ValueError
a)
Test 1: 1200 / 40 + 15 = 30 + 15 = 45, so Cost per student: 45.0.
Test 2: 1200 / 60 + 15 = 20 + 15 = 35, so Cost per student: 35.0.
Test 4: 1200 / 1 + 15 = 1215, so Cost per student: 1215.0.
The expected outcome comes from the specification, before the program runs: copying what the program prints into the plan would make every test pass.
b)
Test 1, 40: 40 > 0 and 40 < 60 are True, and line 5 prints Cost per student: 45.0: pass.
Test 2, 60: 60 < 60 is False, so the else branch prints the message instead of 35.0: fail.
Test 3, 0: 0 > 0 is False, the message: pass. Test 4, 1: Cost per student: 1215.0, pass. Test 5, 61: the message, pass.
Test 6, forty: int('forty') stops the program with a traceback, and the message never appears: fail.
2 tests fail, tests 2 and 6 (solution figure).
c)
Test 2 runs to its end with no message from Python and prints a wrong outcome: a logic error, in line 3, where < 60 excludes the boundary 60 that the specification includes.
Test 6 stops while the program runs: a run-time error. The last line of the traceback reads ValueError: invalid literal for int() with base 10: 'forty', and the line above it names line 2, where int() received the text.
Pitfall: a logic error stops nothing: the program runs and prints a wrong outcome, which the comparison with an expected outcome computed by hand reveals.
d)
Four classes of inputs: a text that is not a whole number; the whole numbers 0 or less; 1 to 60; 61 or more. Between the whole-number classes, two boundaries: between 0 and 1, and between 60 and 61.
Both sides of each boundary: 0, 1, 60 and 61. These four tests already fall in the three whole-number classes, so one text, such as forty, completes the rule: 5 tests.
Test 1, 40, is the one the rule does not need: a typical value of the class 1 to 60, which the tests 1 and 60 already cover. It is the test that passed while the bug of test 2 was there.
e)
1 <= n <= 60 includes both ends; in Python, this chained comparison means 1 <= n and n <= 60.
n >= 0 and n <= 60 lets 0 in, and line 4 then divides by zero (ZeroDivisionError); n > 0 or n <= 60 is True for every whole number; n > 1 and n <= 60 refuses 1.
Only line 2 can raise ValueError: the try encloses it, the except ValueError prints the message, and the else runs the rest when the conversion worked (solution code).
Pitfall: a try around the whole program with a bare except would also hide an error of line 4 or 5, and the message would no longer say what went wrong.
In Java, 1 <= n <= 60 is refused by the compiler: it is written n >= 1 && n <= 60.
Python
text = input("Students on the trip: ")
try:
n = int(text)
except ValueError:
print("Type a whole number from 1 to 60")
else:
if 1 <= n <= 60:
share = 1200 / n + 15
print("Cost per student:", round(share, 2))
else:
print("Type a whole number from 1 to 60")
Points are earned before the solution; after it, you can keep practising.
For you:
Part D: Communication (/15)
Exercise 10: Communication: the specification, design and schedule of a league app
16 answers to check
Communication, 15 marks, three per part. The marks go to clear wording: say what you choose and why, in complete sentences, with the vocabulary of the course.
The physical education department asks a Grade 11 class, in a project led by the teacher, for an app that runs the sign-ups of the lunch-hour volleyball league. The department head writes: « Students sign up with their 9-digit student number. A team has between 6 and 10 players. Players under 14 need a permission form. The teams are posted on Friday. » In part c), players holds the number of students signed up. In part e), each task is given to one student, so tasks run at the same time whenever they can, and a task starts as soon as the tasks it follows are finished.
Task
Duration (days)
Starts after
A Specification
2
none
B Design
3
A
C Sign-up module
4
B
D Team list module
3
B
E User guide
1
B
F Testing
2
C and D
G Installation
1
E and F
Pseudocode
SET teams TO 1
WHILE players > 10 * teams
SET teams TO teams + 1
END WHILE
DISPLAY teams
a) Before writing code, the class asks two questions. Which question settles the meaning of « between 6 and 10 players », and which one settles « under 14 »?
b) Name the phase of the software development life cycle of each product: the specification signed by the department head; the structure chart of the modules; the bug report of the week of trial sign-ups; the user guide given to the department head when the app is installed; the change made in January, when the league adds a second court.
c) Describe in one sentence what the pseudocode computes. What does it display for 23 players, and for 41? What is the smallest number of players that gives 4 teams?
d) Choose the message the app shows when a student types a student number of 6 digits, and the notice it posts when only 5 players have signed up.
e) From the table of tasks, find the minimum duration of the project and its critical path, the slack of task D and of task E, and the new minimum duration if task D takes 2 days more.
Show the solution
Answers
a)Can a team have exactly 6 players, and exactly 10?; is the age counted on the day of sign-up or on the first day of the league?
c)the smallest number of teams of at most 10 players; 3 teams for 23, 5 for 41; 31 players
d)the message that names the 9 digits expected and the 6 typed; the notice that gives the count, the rule and its effect
e)12 days, critical path A, B, C, F, G; slack of D 1 day, of E 5 days; 13 days
a)
« Between 6 and 10 » may include its ends or not: the question that settles it asks about 6 and 10 themselves, « Can a team have exactly 6 players, and exactly 10? ». The answer decides whether the program writes players >= 6 and players <= 10, or > and <.
« Under 14 » depends on a date, since a student can turn 14 during the league: ask whether the age is counted on the day of sign-up or on the first day of the league.
The other questions ask for facts the program does not need, or for a choice the programmer makes alone.
b)
The specification is the product of the analysis: it writes the inputs, the outputs and the rules the client agrees to, and its signature is a milestone.
The structure chart is a product of the design, drawn before any code.
The bug report of the trial week is a product of testing.
The user guide is delivered with the installation: implementation.
The change in January comes after the app is in use: maintenance, which lasts as long as the app is used.
c)
In one sentence: the pseudocode adds one team at a time until 10 players per team are enough for everyone, so it displays the smallest number of teams of at most 10 players.
23 players: 23 > 10, teams = 2; 23 > 20, teams = 3; 23 > 30 is false: it displays 3.
41 players: the test is true for 10, 20, 30 and 40, false for 50: it displays 5.
4 teams are displayed when players > 30 and players <= 40: 31 is the smallest number, since 30 players fit in 3 teams of 10.
The pseudocode does not check the minimum of 6 players per team: for 11 players it displays 2 teams, and one of them can have only 5 players. The specification has to say what happens then.
d)
A good message says what is wrong and how to fix it, in the user's words: « Your student number has 9 digits; you typed 6. Type it again. » Error! and Invalid input do not say what to change, and the name of a Python exception means nothing to a student.
The notice gives the count, the rule it breaks and what follows from it: « 5 players have signed up; a team needs at least 6, so no team can be formed yet. »
e)
Earliest dates, in days from the start: A 0 to 2, B 2 to 5; then C 5 to 9, D 5 to 8 and E 5 to 6; F starts when C and D are both finished, at 9, and ends at 11; G starts when E and F are finished, at 11, and ends at 12.
Minimum duration: 12 days. The critical path is the longest path, A, B, C, F, G: 2 + 3 + 4 + 2 + 1 = 12 days (solution figure).
Slack of D: D ends at 8 and F can start only at 9, so D can lose 1 day without moving the end. Slack of E: E ends at 6 and G starts at 11, so 5 days.
If D takes 5 days, it ends at 10: F starts at 10 and ends at 12, G ends at 13. The first day of delay uses the slack, the second moves the end: 13 days.
Pitfall: the shortest path, A, B, E, G, 7 days, is not the duration of the project: every task must be finished.
Points are earned before the solution; after it, you can keep practising.
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.
I tutor Grade 11 computer science in English or in French, online. Get in touch for a first session on the questions where you lost marks, or on your final project.