ICS3U Computer Science • Ontario Grade 11

Corrected exercises: strings and built-in subprograms (ICS3U)

Exercises: strings and built-in subprograms (ICS3U)

Name: Class: Date:

Solutions

Suggested time: 2 h 30 · No calculator · 12 exercises
https://www.letuteurscientifique.ca/en/exercices/ics3u-strings-built-in-subprograms

These ten corrected exercises, preceded by two lists of direct calculations, cover the fourth chapter of ICS3U, Introduction to Computer Science, Grade 11, University Preparation, in Ontario: the string data type, its indices from 0 and from the end, substrings taken by slices, assignment statements with string expressions (concatenation, a string built in a loop), and the existing subprograms of the course, the random number generator (randint, randrange, random), the absolute value, the substring and string methods (upper, lower, strip, replace, count, find), and len, round, max, min, str, int and format.

What the set covers, the traps it targets

The code is in Python 3; indices, traces and the reading of a call by what goes in and what comes out work the same way in any language, and a line of the solutions says where Java behaves differently.

Exercise 0.1 evaluates ten indices and slices, exercise 0.2 ten calls of built-in subprograms. By the end, you can read the fields of an Ontario course code with indices and slices (exercise 1), see why a username keeps its spaces after strip() and store a method's result (exercise 2), give the smallest value, the largest value and the number of values of a random call (exercise 3), and build a string in a loop, on a masked student number (exercise 4), and repair a receipt that joins a str and an int, with round, format and min (exercise 5). Part B converts digits read as text before comparing them, at a silent auction (exercise 6), computes the length of a train trip from times stored as strings, overnight included (exercise 7), corrects five statements (exercise 8), encrypts and decrypts a transposition cipher on two rails (exercise 9), and writes a program that gives the complement and the GC content of a DNA strand (exercise 10).

The thread of the set: a string is a row of characters numbered from 0, and it never changes; a slice, a method or a built-in function gives back a new value, lost unless it is stored or displayed, so every call is read by what goes in, what comes out, and the type and the range of what comes out. Five traps are named in the solutions: (1) forgetting that the first character has index 0 and that the end of a slice is excluded, exercises 0.1, 1, 4, 7, 8 and 9; (2) calling s.upper() or s.strip() without storing the result, since a string never changes, exercises 2, 8 and 10; (3) taking randrange(a, b) for randint(a, b), when only randint can give back b, exercises 3 and 8; (4) joining a str and an int with +, a TypeError, exercises 0.2, 1, 5 and 8; (5) comparing digits read by input() as text, so that 95 beats 120, exercise 6. Also treated: a single index outside the string raises an IndexError while a slice never does (0.1, 1, 9), abs that hides a wrong count (7), round against format for an amount of money (5), and replace calls chained on letters that are exchanged (10).

No calculator is needed: every index, every slice and every trace is worked out by hand, as on a unit test.

  • 12 corrected exercises • 120 points • 150 minutes
  • Self-checking, 108 answers
  • No calculator
Start exercise 0.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

  • • The characters of s have the indices 0 to len(s) - 1; s[-1] is the last character.
  • • s[a:b] takes the indices a to b - 1: the end is excluded. s[:b] starts at 0, s[a:] runs to the end.
  • • A single index outside the string raises an IndexError; a slice stops at the end of the string without error.
  • • A string never changes: s.upper(), s.lower(), s.strip(), s.replace(a, b) give back new strings. Store them: s = s.strip().
  • • + joins two strings or adds two numbers, never a str and an int: 'Total: ' + str(12).
  • • random.randint(a, b) gives a to b, b included; random.randrange(a, b) gives a to b - 1; random.random() gives a float from 0 included to 1 excluded.
  • • abs(x) is the distance to 0; round(x, n) keeps n decimals; format(x, '.2f') displays two decimals.
  • • input() gives back a str: convert digits with int() or float() before comparing or computing.

Calculations: indices and slices

Exercise 0.1: Indices and slices: ten expressions to evaluate

10 answers to check

The variable s holds the string 'ALGORITHM'. Give the value of each expression, or the error that Python raises.

Method: the characters are numbered from 0 on the left, so the last one has the index len(s) - 1; a negative index counts from the end, -1 being the last character. A slice s[a:b] takes the characters from index a up to index b, b excluded; without a it starts at the beginning, without b it runs to the end. An index outside the string raises an IndexError; a slice never does.

  • a) len(s)
  • b) s[1]
  • c) s[8]
  • d) s[9]
  • e) s[-2]
  • f) s[2:5]
  • g) s[:3]
  • h) s[6:]
  • i) s[5:50]
  • j) len(s[3:7])

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

a)
b)
c)
d)
e)
f)
g)
h)
i)
j)
Show the solution

Answers

  • a) 9
  • b) 'L'
  • c) 'M': the last index is 8
  • d) IndexError
  • e) 'H'
  • f) 'GOR': indices 2, 3 and 4
  • g) 'ALG'
  • h) 'THM'
  • i) 'ITHM', no error
  • j) 4, that is 7 - 3

Write the indices under the letters: A 0, L 1, G 2, O 3, R 4, I 5, T 6, H 7, M 8. The negative indices run from -9 under the A to -1 under the M.

a)

len counts the characters: 9. The indices go from 0 to 9 - 1 = 8.

b)

s[1] is the second character: 'L'.

Pitfall: counting from 1 and answering 'A', which is s[0].

c)

s[8] is 'M', the last character: its index is len(s) - 1 = 8.

d)

s[9] asks for a tenth character, which does not exist: IndexError: string index out of range. The program stops on that line.

e)

-1 is the 'M' and -2 the 'H': s[-2] is the same character as s[9 - 2], that is s[7].

In Java, a negative index is an error: the last character is s.charAt(s.length() - 1).

f)

s[2:5] takes the indices 2, 3 and 4: 'GOR', 5 - 2 = 3 characters.

Pitfall: including s[5] and answering 'GORI'. The end of a slice is excluded.

g)

s[:3] starts at index 0 and stops before index 3: 'ALG', the first 3 characters.

h)

s[6:] runs from index 6 to the end: 'THM'.

i)

A slice whose end goes past the string stops at its last character: s[5:50] is s[5:], 'ITHM'.

No error: only a single index outside the string raises an IndexError.

j)

s[3:7] is 'ORIT', and its length is 7 - 3 = 4. Inside the string, a slice s[a:b] has b - a characters.

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.

Calculations: built-in subprograms

Exercise 0.2: Built-in subprograms: ten calls to evaluate

10 answers to check

The variable word holds the string 'Grade 11', with one space between the e and the first 1. Give the value of each call, or the error that Python raises.

Method: a method is written after a dot, word.upper(), and a function takes its values in brackets, len(word). Each one gives back a new value and changes nothing: what matters is the value it gives back, and its type.

  • a) len(word)
  • b) word.upper()
  • c) word.replace('1', '2')
  • d) word.count('1')
  • e) abs(3 - 10)
  • f) round(7.46, 1)
  • g) round(7.46)
  • h) max(4, -9, 2) - min(4, -9, 2)
  • i) str(12) + '5'
  • j) 'Total: ' + 12

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

a)
b)
c)
d)
e)
f)
g)
h)
i)
j)
Show the solution

Answers

  • a) 8: the space counts
  • b) 'GRADE 11'
  • c) 'Grade 22'
  • d) 2
  • e) 7
  • f) 7.5
  • g) 7
  • h) 13, that is 4 - (-9)
  • i) '125', a string
  • j) TypeError

Read each call in two steps: what goes in, in the brackets or before the dot, then what comes out, with its type.

a)

len counts every character, the space included: G, r, a, d, e, the space, 1, 1, that is 8.

b)

upper() gives back a copy in capital letters: 'GRADE 11'. Digits and spaces have no capital form and stay as they are.

word itself still holds 'Grade 11'.

c)

replace('1', '2') replaces every '1', not only the first one: 'Grade 22'.

d)

count('1') gives back how many times '1' appears: 2, an int.

e)

The brackets first: 3 - 10 = -7. abs gives the distance to 0: 7.

f)

round(7.46, 1) keeps one decimal: the next digit, 6, is 5 or more, so 7.5.

g)

round with a single value gives back the nearest whole number, an int: 7, since 7.46 is nearer to 7 than to 8.

h)

max(4, -9, 2) is 4 and min(4, -9, 2) is -9, so 4 - (-9) = 13.

i)

str(12) is the string '12', and + between two strings joins them: '125'. int('12') + 5 would add, and give 17.

j)

'Total: ' is a str and 12 an int: + cannot join them, and Python raises TypeError: can only concatenate str (not "int") to str.

Write 'Total: ' + str(12), or print('Total:', 12), which separates its values by a space. In Java, "Total: " + 12 is accepted and gives Total: 12.

Part A: the basics (/50)

Exercise 1: Indices and slices: reading an Ontario course code

7 answers to check

In Ontario, a secondary-school course has a five-character common course code: three letters for the subject, one digit for the grade (1 for Grade 9, 2 for Grade 10, 3 for Grade 11, 4 for Grade 12), then one letter for the type of course, such as U for university preparation or C for college preparation. The figure shows the three fields of the code SCH3U. A course-selection program splits a code into its fields.

SCH3UsubjectgradetypeThe three fields of the code SCH3U
Python
code = 'SCH3U'                    # line 1
subject = code[0:3]               # line 2
grade = int(code[3]) + 8          # line 3
kind = code[-1]                   # line 4
print(subject, grade, kind)       # line 5
  • a) What does line 5 print?
  • b) A classmate writes subject = code[1:3] on line 2 and kind = code[5] on line 4. What is the value of code[1:3]? What happens when Python reaches line 4?
  • c) Each of these four expressions is meant to give '3U', the grade and the type together: code[3:5] ; code[3:] ; code[-2:] ; code[3:4]. How many of them give '3U'?
  • d) A student leaves out int on line 3 and writes grade = code[3] + 8. What happens?
  • e) A school timetable may add a sixth character of its own after the five, for a section: SCH3U1. What does the program print for this code? Which line 4 gives the type for a code of five characters and for a code of six?

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

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

Answers

  • a) SCH 11 U
  • b) 'CH'; IndexError: string index out of range
  • c) 3: all of them except code[3:4]
  • d) TypeError: + between a str and an int
  • e) SCH 11 1; kind = code[4]

The fields sit at fixed places counted from the left: the subject at the indices 0, 1 and 2, the grade at index 3, the type at index 4. The figure below writes the positive indices under the characters and the negative ones above them.

a)

Line 2: code[0:3] takes the indices 0, 1 and 2: 'SCH'.

Line 3: code[3] is the string '3', int('3') is 3, and 3 + 8 = 11.

Line 4: code[-1] is the last character, 'U'.

print separates its values by a space: SCH 11 U.

b)

code[1:3] takes the indices 1 and 2: 'CH'. The subject loses its first letter, and no error warns about it.

The last index of a five-character string is 4: code[5] stops the program with IndexError: string index out of range.

Pitfall: counting the characters from 1, which shifts every field one place to the right.

c)

code[3:5] takes the indices 3 and 4: '3U'. code[3:] runs from index 3 to the end: '3U'. code[-2:] takes the last two characters: '3U'.

code[3:4] stops before index 4: '3', a single character. 3 expressions out of 4 give '3U'.

d)

code[3] is the string '3', and + between a str and an int is refused: TypeError: can only concatenate str (not "int") to str.

int(code[3]) converts the digit first, and the addition becomes 3 + 8.

e)

For SCH3U1, lines 2 and 3 still read 'SCH' and 3: the fields counted from the left have not moved. code[-1] is now '1', the section, and the program prints SCH 11 1.

The type is always at index 4: kind = code[4] works for both lengths. A negative index counts from the end, so the character it reaches changes when the string grows.

In Java, a negative index is an error: the last character is code.charAt(code.length() - 1).

S0-5C1-4H2-333-2U4-1code = 'SCH3U': code[4] and code[-1] are both 'U'S0-6C1-5H2-433-3U4-215-1code = 'SCH3U1': code[-1] is now '1', code[4] is still 'U'

Exercise 2: A string never changes: cleaning a username

7 answers to check

A coding club's sign-up program stores every username in lower case, without the spaces a user may type before or after it. strip() gives back a copy without the spaces at both ends; lower() gives back a copy in lower case. A user types two spaces, Maya_K, then two spaces. The brackets printed on line 4 show where the string starts and ends.

Python
name = input('Username: ')            # line 1
name.strip()                          # line 2
name.lower()                          # line 3
print('[' + name + ']', len(name))    # line 4
  • a) What does line 4 print?
  • b) Why do lines 2 and 3 change nothing?
  • c) Lines 2 and 3 are replaced by a single line that keeps the result. Which line? What does len(name) give then?
  • d) After this correction, a student adds print(name.upper()), then print(name). What does the second of these two lines print?
  • e) To give the name a capital first letter, a student writes name[0] = 'M'. What happens? What value does name[0].upper() + name[1:] give for name = 'maya_k'?

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

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

Answers

  • a) [ Maya_K ] 10
  • b) strip() and lower() give back new strings, and nothing stores them: name is unchanged
  • c) name = name.strip().lower(); 6
  • d) maya_k
  • e) TypeError; 'Maya_k'

A string cannot be modified: a method such as strip() or lower() builds a new string and gives it back. That new string is lost unless an assignment stores it, usually in the same variable: name = name.strip().

a)

Line 1 stores ' Maya_K ': 2 + 6 + 2 = 10 characters.

Line 2 computes 'Maya_K' and line 3 computes ' maya_k ', and both values are thrown away.

Line 4 prints [ Maya_K ] 10.

b)

strip() and lower() give back new strings and leave name as it was; no assignment stores their results. Python gives no error and no warning.

Pitfall: reading name.lower() as an order given to name. It asks name for a new string, which must be stored.

c)

name = name.strip().lower(): strip() gives 'Maya_K', lower() is called on that new string and gives 'maya_k', and = stores it in name.

Line 4 then prints [maya_k] 6: len(name) is 6.

d)

print(name.upper()) displays MAYA_K, a new string built for the display only. name still holds 'maya_k', so the second line prints maya_k.

e)

A string refuses an assignment to one of its characters: TypeError: 'str' object does not support item assignment.

A new string is built from pieces instead: name[0].upper() is 'M', name[1:] is 'aya_k', and + joins them into 'Maya_k'. To keep it, write name = name[0].upper() + name[1:].

Exercise 3: randint or randrange: what a random call can give back

12 answers to check

A trivia app keeps a bank of 40 questions, numbered from 1 to 40, and picks one at random with the module random. Its documentation says: random.randint(a, b) gives back a whole number N with a ≤ N ≤ b; random.randrange(a, b) gives back a whole number from a up to b, b excluded; random.randrange(a, b, step) starts at a and moves by step, b excluded; random.random() gives back a float x with 0 ≤ x < 1. Each possible result of one call is equally likely.

Python
import random                                 # line 1
question = random.randrange(1, 40)            # line 2
bonus = abs(random.randint(-5, 5))            # line 3
print('Question', question, 'bonus', bonus)   # line 4
  • a) Give the smallest and the largest value that line 2 can give back. Which question of the bank is never asked?
  • b) Each of these four calls is meant to give back any whole number from 1 to 40: random.randint(1, 40) ; random.randrange(1, 41) ; random.randrange(0, 40) + 1 ; random.randint(0, 40). How many of them do it?
  • c) On line 3, random.randint(-5, 5) can give back 11 whole numbers. How many different values can bonus take? Give its smallest and its largest value.
  • d) Among the 11 numbers that random.randint(-5, 5) can give back, how many give bonus = 3? How many give bonus = 0? Are the values of bonus equally likely?
  • e) How many different values can random.randrange(10, 50, 10) give back? Give, as an interval, the set of values that random.random() can give back.

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

a)
b)
c)
d)
e)
Values of random.random() ,
Show the solution

Answers

  • a) 1 and 39; question 40
  • b) 3: all of them except random.randint(0, 40)
  • c) 6 values, from 0 to 5
  • d) 2 numbers (-3 and 3); 1 number; no
  • e) 4 values: 10, 20, 30, 40; {x ∈ ℝ | 0 ≤ x < 1}, the interval [0, 1)

The two calls differ at their upper end: randint(a, b) includes b, randrange(a, b) excludes it, like range(a, b). The table below gives, for each call of the exercise, its smallest value, its largest value and how many values it can give back.

a)

random.randrange(1, 40) gives back a whole number from 1 to 39, since 40 is excluded: smallest 1, largest 39.

Question 40 is never asked, and no error shows it: the documentation, or a test that counts the questions drawn, reveals it.

Pitfall: reading randrange(1, 40) as if it were randint(1, 40).

b)

random.randint(1, 40) gives 1 to 40. random.randrange(1, 41) gives 1 to 40, since 41 is excluded. random.randrange(0, 40) gives 0 to 39, plus 1: 1 to 40.

random.randint(0, 40) can give back 0, a question that does not exist: 41 values. 3 calls out of 4 do it.

c)

abs gives the distance to 0: -5 and 5 both give 5, -4 and 4 give 4, and so on down to 0, which gives 0.

bonus takes the 6 values 0, 1, 2, 3, 4 and 5: smallest 0, largest 5.

d)

bonus = 3 comes from two numbers, -3 and 3; bonus = 0 from one number only, 0.

The 11 numbers are equally likely, so bonus = 3 comes out twice as often as bonus = 0, on average: the values of bonus are not equally likely.

A bonus from 0 to 5 whose values are equally likely is random.randint(0, 5).

e)

random.randrange(10, 50, 10) starts at 10 and moves by 10, with 50 excluded: 10, 20, 30, 40, that is 4 values.

random.random() gives back x with 0 ≤ x < 1: {x ∈ ℝ | 0 ≤ x < 1}, the interval [0, 1), 0 included and 1 excluded. Java's Math.random() has the same range.

Call (module random)SmallestLargestValuesrandrange(1, 40)13939randint(1, 40)14040randrange(1, 41)14040randrange(0, 40) + 114040randint(0, 40)04041abs(randint(-5, 5))056randrange(10, 50, 10)10404Each call of the exercise, from its smallest to its largest value

Exercise 4: Building a string in a loop: masking a student number

7 answers to check

A school portal displays a student number with every digit hidden by a star, except the last four. The number is stored as a string of nine digits.

Python
number = '342071865'                    # line 1
masked = ''                             # line 2
for i in range(len(number)):            # line 3
    if i < len(number) - 4:             # line 4
        masked = masked + '*'           # line 5
    else:                               # line 6
        masked = masked + number[i]     # line 7
print(masked)                           # line 8
  • a) How many passes does the loop make? How many times does line 5 run?
  • b) What does line 8 print?
  • c) What does masked hold at the end of the pass where i is 6?
  • d) A student writes if i <= len(number) - 4: on line 4. How many digits does the portal show then?
  • e) Which single line gives the same result as lines 2 to 7, for a number of any length? For a twelve-digit number, how many stars does it display?

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

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

Answers

  • a) 9 passes; 5 times
  • b) *****1865
  • c) '*****18'
  • d) 3 digits: ******865
  • e) masked = '*' * (len(number) - 4) + number[-4:]; 8 stars

The loop visits the indices 0 to 8, one per pass, and each pass adds one character at the end of masked: a star while i < 5, the digit number[i] from i = 5 on. The trace table below follows the nine passes.

a)

len(number) is 9, so range(len(number)) gives 9 passes, i from 0 to 8.

Line 4 compares i with 9 - 4 = 5: i < 5 holds for i = 0, 1, 2, 3 and 4, so line 5 runs 5 times and line 7 runs 4 times.

b)

Five stars, then number[5], number[6], number[7] and number[8], that is 1, 8, 6 and 5: *****1865.

c)

After the pass i = 4, masked holds five stars. The pass i = 5 adds '1' and the pass i = 6 adds number[6], '8': '*****18'.

d)

With <=, the pass i = 5 also adds a star: 6 stars, then number[6] to number[8], that is ******865, 3 digits.

Pitfall: < against <= on a bound computed from len. The shift is one character, and no error shows it: counting the characters does.

e)

'*' * (len(number) - 4) repeats the star len(number) - 4 times, and number[-4:] takes the last four characters whatever the length: masked = '*' * (len(number) - 4) + number[-4:].

For twelve digits, 12 - 4 = 8 stars, then the last four digits.

masked = '' stays on line 2, before the loop: written inside the loop, it would empty the string at every pass, and line 8 would print the last digit alone.

ii < 5Addedmasked after the pass0True**1True***2True****3True*****4True******5False1*****16False8*****187False6*****1868False5*****1865Trace of the loop, one row per pass

Exercise 5: str and int do not mix: a bike-share receipt

9 answers to check

A bike-share system charges 1.25 dollars to unlock a bike, then 0.15 dollars per minute, and prints a receipt at the end of the trip. The program below stops with an error on its first test.

Python
UNLOCK = 1.25                                  # line 1
PER_MINUTE = 0.15                              # line 2
minutes = int(input('Minutes: '))              # line 3
cost = UNLOCK + PER_MINUTE * minutes           # line 4
print('Trip: ' + minutes + ' min')             # line 5
print('Cost: ' + str(cost) + ' dollars')       # line 6
  • a) The user types 18. What happens at line 5? Does line 6 run?
  • b) Which line 5 prints Trip: 18 min?
  • c) With line 5 corrected, the program displays Cost: 3.9499999999999997 dollars for 18 minutes. Which expression, placed in the brackets of str on line 6, makes it display 3.95?
  • d) For 15 minutes, what does line 6 display with str(round(cost, 2))? And with format(cost, '.2f') in place of str(cost)?
  • e) The system caps the price of a trip at 6.00 dollars. Which line 4 applies the cap? With it, what does a 40-minute trip cost? From how many whole minutes does the cap change the price?

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

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

Answers

  • a) TypeError; no
  • b) print('Trip: ' + str(minutes) + ' min')
  • c) round(cost, 2)
  • d) Cost: 3.5 dollars; Cost: 3.50 dollars
  • e) cost = min(UNLOCK + PER_MINUTE * minutes, 6.00); 6.00 dollars; from 32 minutes

In Python, + adds two numbers or joins two strings, never a string and a number: a number that enters a sentence built with + goes through str() first. The corrected program, cap included, is below.

a)

minutes holds the int 18, and 'Trip: ' + minutes joins a str and an int: TypeError: can only concatenate str (not "int") to str.

The program stops at line 5, so line 6 never runs.

In Java, "Trip: " + 18 is accepted and gives Trip: 18, which is why this error surprises students who started with Java.

b)

print('Trip: ' + str(minutes) + ' min') converts 18 to '18' first. print('Trip:', minutes, 'min') also works, since print converts each value and separates them by a space.

'Trip: ' + 'minutes' + ' min' joins the word minutes, not its value, and int(minutes) is still an int: TypeError again.

c)

0.15 × 18 = 2.7 and 1.25 + 2.7 = 3.95, but the computer stores most decimal numbers in binary with a tiny error, which str() shows in full. How such errors arise is studied in Grade 12 (ICS4U).

round(cost, 2) gives back the nearest number with two decimals, 3.95: str(round(cost, 2)) displays 3.95.

d)

15 minutes: 1.25 + 0.15 × 15 = 1.25 + 2.25 = 3.5. round(3.5, 2) is still 3.5, since a float keeps no zero at its end: Cost: 3.5 dollars.

format(cost, '.2f') gives back a string with two decimals, '3.50': Cost: 3.50 dollars. For an amount of money, round computes and format displays.

e)

min gives back the smaller of its values: cost = min(UNLOCK + PER_MINUTE * minutes, 6.00) keeps the formula while it is under 6.00, and 6.00 above.

40 minutes: 1.25 + 0.15 × 40 = 7.25, so min(7.25, 6.00) = 6.00 dollars.

The cap changes the price once 1.25 + 0.15 × m > 6.00, that is m > 4.75 / 0.15 = 31.67: 31 minutes cost 5.90 dollars, and 32 minutes would cost 6.05 dollars without the cap. From 32 minutes.

Pitfall: max(..., 6.00) in place of min, which charges at least 6.00 dollars for every trip.

Python
UNLOCK = 1.25        # dollars
PER_MINUTE = 0.15    # dollars per minute
CAP = 6.00           # dollars
minutes = int(input('Minutes: '))
cost = min(UNLOCK + PER_MINUTE * minutes, CAP)
print('Trip: ' + str(minutes) + ' min')
print('Cost: ' + format(cost, '.2f') + ' dollars')

Part B: problems and reasoning (/50)

Exercise 6: Digits compared as text: 95 beats 120 at a silent auction

7 answers to check

At a school's silent auction, two people bid on the same item, and a program announces the higher bid. Bids are whole numbers of dollars. Its first test, with bids of 95 and 120 dollars, announces the wrong winner.

Python
bid1 = input('First bid (dollars): ')      # line 1
bid2 = input('Second bid (dollars): ')     # line 2
best = max(bid1, bid2)                     # line 3
print('Winning bid:', best)                # line 4
  • a) What does line 4 print for the bids 95 and 120?
  • b) What does max compare on line 3?
  • c) For how many of these five pairs of bids does the program as written announce the right winner: 95 and 120 ; 85 and 95 ; 100 and 99 ; 250 and 1000 ; 300 and 450?
  • d) Which correction makes the program right for every pair of whole bids? What does it print for 95 and 120?
  • e) Before the correction, a student adds a reserve price after line 4: if best >= 100: print('Sold'). What happens for 95 and 120? And after the correction?

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

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

Answers

  • a) Winning bid: 95
  • b) Two strings, character by character from the left
  • c) 2 pairs: 85 and 95, 300 and 450
  • d) bid1 = int(input('First bid (dollars): ')), and the same for bid2; Winning bid: 120
  • e) TypeError, a str compared with an int; Sold

input() gives back a string, and max compares two strings as text: the first characters first, then the second ones only if the first are equal, as in a dictionary. The rules of string comparison are studied in Grade 12 (ICS4U); in this course, the gesture is to convert a number before comparing it.

a)

bid1 holds '95' and bid2 holds '120'. The first characters are '9' and '1', and '9' comes after '1' among the digits, so '95' is the larger string.

Line 4 prints Winning bid: 95.

b)

max compares two strings, character by character from the left; neither the length nor the value of the numbers plays a part. The table below gives the first characters of each pair.

Pitfall: trusting input() to read a number because the user types digits. It gives back a str.

c)

95 and 120: '9' after '1', the program announces 95, wrong. 85 and 95: '9' after '8', 95, right. 100 and 99: '9' after '1', 99, wrong. 250 and 1000: '2' after '1', 250, wrong. 300 and 450: '4' after '3', 450, right.

2 pairs out of 5. For whole numbers written with the same number of digits, the text order and the number order agree, which is why tests with two-digit bids only do not reveal the bug.

d)

bid1 = int(input('First bid (dollars): ')), and the same on line 2: max then compares two int, and the program prints Winning bid: 120.

best = max(int(bid1), int(bid2)) on line 3 also works; converting at the input keeps every later line safe.

e)

Before the correction, best is a str, and best >= 100 compares a str with an int: TypeError: '>=' not supported between instances of 'str' and 'int'. Python 3 refuses that comparison.

After the correction, best is 120, 120 >= 100 is True, and the program prints Sold.

In Java, < and > do not compile between two Strings: text is compared with compareTo.

BidsFirst charactersmax as textmax as numbers95 and 120'9' and '1'9512085 and 95'8' and '9'9595100 and 99'1' and '9'99100250 and 1000'2' and '1'2501000300 and 450'3' and '4'450450max on strings compares the first characters first

Exercise 7: Times stored as strings: the length of a train trip

10 answers to check

A trip planner reads the departure and arrival times of a train in the form HH:MM, always with five characters: 08:47, 23:40. It converts each time to minutes after midnight, then subtracts. The timetable gives two trips.

TrainDepartsArrivesDay train08:4710:15Night train23:4000:25, the next dayTimetable
Python
dep = input('Departure (HH:MM): ')           # line 1
arr = input('Arrival (HH:MM): ')             # line 2
d = int(dep[0:2]) * 60 + int(dep[3:5])       # line 3
a = int(arr[0:2]) * 60 + int(arr[3:5])       # line 4
print('Trip:', a - d, 'min')                 # line 5
  • a) For the day train, what values do d and a take? What does line 5 print?
  • b) A classmate writes int(dep[3:4]) and int(arr[3:4]) for the minutes on lines 3 and 4. What length does line 5 print for the day train?
  • c) What length does the program as written print for the night train?
  • d) A student repairs it with print('Trip:', abs(a - d), 'min'). What does it print for the night train? How long is the trip really?
  • e) Which correction gives the right length for both trains? The program then displays the length in hours and minutes with // and %: how many hours and how many minutes for the day train?

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

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

Answers

  • a) d = 527, a = 615; Trip: 88 min
  • b) 117 min
  • c) -1395 min
  • d) 1395 min; 45 min
  • e) if diff < 0: diff = diff + 1440; 1 h 28 min

Each time has its fields at fixed places: the hours at the indices 0 and 1, the colon at index 2, the minutes at 3 and 4. The slices [0:2] and [3:5] take two characters each, and int converts them, as the figure below shows. The corrected program is below it.

a)

08:47: int('08') = 8 and int('47') = 47, so d = 8 × 60 + 47 = 527. int accepts the leading zero.

10:15: a = 10 × 60 + 15 = 615.

Line 5 prints Trip: 88 min, since 615 - 527 = 88.

b)

dep[3:4] stops before index 4: '4' in place of '47', so d = 480 + 4 = 484. arr[3:4] is '1', so a = 600 + 1 = 601.

Line 5 prints Trip: 117 min.

Pitfall: reading the end of a slice as its last index. Two characters from index 3 is [3:5].

c)

23:40 gives d = 23 × 60 + 40 = 1420, and 00:25 gives a = 25: a - d = 25 - 1420 = -1395, and line 5 prints Trip: -1395 min.

The train arrives the next day, when the minutes after midnight start again at 0.

d)

abs(-1395) is 1395: Trip: 1395 min, about 23 hours. abs removes the sign; it does not repair the count.

The real length: 20 minutes until midnight, then 25 minutes, that is 45 minutes. A day has 24 × 60 = 1440 minutes, and -1395 + 1440 = 45.

e)

diff = a - d, then if diff < 0: diff = diff + 1440. For the night train, diff becomes 45; for the day train, diff is 88 and stays 88.

88 // 60 = 1 and 88 % 60 = 28: Trip: 1 h 28 min. The correction assumes a trip shorter than one day, as on this timetable.

Python
dep = input('Departure (HH:MM): ')
arr = input('Arrival (HH:MM): ')
d = int(dep[0:2]) * 60 + int(dep[3:5])
a = int(arr[0:2]) * 60 + int(arr[3:5])
diff = a - d
if diff < 0:
    diff = diff + 1440    # the train arrives the next day
print('Trip:', diff // 60, 'h', diff % 60, 'min')
0081:24374dep[0:2] is '08'dep[3:5] is '47'dep[3:4] stops before index 4: '4' only

Exercise 8: Five statements to correct

10 answers to check

Each statement below was written by a student revising this chapter. Say whether it is true or false, then answer the question that follows it. Each false statement is corrected in the solution.

  • a) « After s = 'canoe' and then the line s.upper(), the variable s holds 'CANOE'. » What does s hold?
  • b) « random.randrange(1, 10) can give back 10. » What is the largest value it can give back?
  • c) « 'canoe'[1:3] is 'can'. » What is 'canoe'[1:3]?
  • d) « 'Score: ' + str(9 + 1) gives the string 'Score: 91'. » What does it give?
  • e) « For every string s of at least two characters, len(s[2:]) equals len(s) - 2. » What is len('canoe'[2:])?

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

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

Answers

  • a) False; 'canoe'
  • b) False; 9
  • c) False; 'an'
  • d) False; 'Score: 10'
  • e) True; 3

A statement about a string is settled by one exact string and one exact value: here s = 'canoe', whose indices run from 0 under the c to 4 under the e.

a)

False. upper() gives back 'CANOE' and leaves s unchanged; nothing stores the result, so s holds 'canoe'.

Correct statement: « After s = s.upper(), the variable s holds 'CANOE'. »

b)

False. randrange excludes its end: random.randrange(1, 10) gives back a whole number from 1 to 9, so 9 at most.

Correct statement: « random.randint(1, 10) can give back 10 », or « random.randrange(1, 11) can give back 10 ».

c)

False. [1:3] takes the indices 1 and 2: 'an'. 'can' is 'canoe'[0:3], the first three characters.

Correct statement: « 'canoe'[0:3] is 'can' ».

d)

False. The brackets first: 9 + 1 = 10, an int; str(10) is '10', and + joins the two strings: 'Score: 10'. To get 91, the digits are joined as strings: str(9) + str(1).

Correct statement: « 'Score: ' + str(9 + 1) gives 'Score: 10' ».

e)

True. s[2:] keeps every character but the first two, so len(s) - 2 of them: 'canoe'[2:] is 'noe', of length 3 = 5 - 2.

The condition matters: for a string of one character, s[2:] is the empty string, of length 0, while len(s) - 2 is -1.

Exercise 9: Cryptography: a transposition cipher on two rails

11 answers to check

Cryptography, one of the research areas of computer science, also studies ciphers that move letters instead of replacing them. The rail fence cipher on two rails writes the message in a zigzag on two rows, then reads the top row followed by the bottom row. The figure encrypts SECRET: S, C and E go on the top rail, E, R and T on the bottom rail, and the cipher is SCEERT. The letters of the top rail have the even indices 0, 2, 4, ..., those of the bottom rail the odd indices 1, 3, 5, ....

SECRETtop railbottom railtop: SCEbottom: ERTCipher: top then bottom, SCE + ERT = SCEERT
Python
message = 'BRINGSNACKS'                 # line 1
top = ''                                # line 2
bottom = ''                             # line 3
for i in range(len(message)):           # line 4
    if i % 2 == 0:                      # line 5
        top = top + message[i]          # line 6
    else:                               # line 7
        bottom = bottom + message[i]    # line 8
print(top + bottom)                     # line 9
  • a) What does line 9 print? How many letters does top hold at the end?
  • b) What do top and bottom hold at the end of the pass where i is 4?
  • c) To decrypt a cipher, the receiver computes half = (len(cipher) + 1) // 2, takes top = cipher[:half] and bottom = cipher[half:], then rebuilds the message: its letter of index i is top[i // 2] when i is even, bottom[i // 2] when i is odd. For a cipher of 11 letters, what is half? Decrypt LNHTONUCANO.
  • d) A classmate computes half = len(cipher) // 2. What happens when the program decrypts LNHTONUCANO? For a cipher of 10 letters, do the two formulas give the same half?
  • e) How many times does the letter N appear in the cipher of BRINGSNACKS, and in BRINGSNACKS itself? What does a transposition cipher keep from the message?

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

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

Answers

  • a) BIGNCSRNSAK; 6 letters
  • b) top = 'BIG', bottom = 'RN'
  • c) half = 6; LUNCHATNOON
  • d) IndexError at i = 10; yes, both give 5
  • e) 2 and 2; every letter, as many times, in another order

Each pass sends one letter to one of two accumulators: the even indices to top, the odd ones to bottom. The figure colours the letters of BRINGSNACKS by rail; the decryption program of question c) is below.

a)

BRINGSNACKS has the indices 0 to 10. Even indices 0, 2, 4, 6, 8, 10: B, I, G, N, C, S, so top = 'BIGNCS', 6 letters. Odd indices 1, 3, 5, 7, 9: R, N, S, A, K, so bottom = 'RNSAK'.

Line 9 prints BIGNCSRNSAK. With an odd length, 11, the top rail gets one letter more than the bottom rail.

b)

The passes i = 0, 2 and 4 add B, I and G to top; the passes i = 1 and 3 add R and N to bottom: top = 'BIG' and bottom = 'RN'.

c)

half = (11 + 1) // 2 = 6: the top rail of an 11-letter message holds 6 letters. top = 'LNHTON' and bottom = 'UCANO'.

i = 0: top[0], L; i = 1: bottom[0], U; i = 2: top[1], N; i = 3: bottom[1], C; i = 4: top[2], H; i = 5: bottom[2], A; i = 6: top[3], T; i = 7: bottom[3], N; i = 8: top[4], O; i = 9: bottom[4], O; i = 10: top[5], N.

The message is LUNCHATNOON.

d)

half = 11 // 2 = 5 gives top = 'LNHTO' and bottom = 'NUCANO': the cut falls one letter too early, and the letters come out in the wrong order. At i = 10 the program asks for top[5], a sixth character that top does not have: IndexError: string index out of range, before anything is printed.

For 10 letters, (10 + 1) // 2 = 5 and 10 // 2 = 5: the two formulas differ for odd lengths only, so a test plan tries an even length and an odd length.

e)

BIGNCSRNSAK has an N at the indices 3 and 7, and BRINGSNACKS at the indices 3 and 6: 'BIGNCSRNSAK'.count('N') and 'BRINGSNACKS'.count('N') both give 2.

A transposition keeps every letter, as many times as in the message, and changes only their order. Equal letter counts are a first clue that a cipher is a transposition.

Python
cipher = 'LNHTONUCANO'
half = (len(cipher) + 1) // 2
top = cipher[:half]
bottom = cipher[half:]
plain = ''
for i in range(len(cipher)):
    if i % 2 == 0:
        plain = plain + top[i // 2]
    else:
        plain = plain + bottom[i // 2]
print(plain)
B0R1I2N3G4S5N6A7C8K9S10Even indices go to top, odd indices to bottomtop = 'BIGNCS'bottom = 'RNSAK'

Exercise 10: Problem: a DNA strand, its complement and its GC content

8 answers to check

Bioinformatics, where computer science meets biology, treats a DNA strand as a string written with four letters, the bases A, C, G and T. On the paired strand, every A faces a T, every T an A, every C a G and every G a C: the figure pairs the bases of a short example. The GC content of a strand is the percentage of its bases that are G or C.

Write a program that reads a strand, accepts it in lower or upper case, and displays its complement, base by base, then its GC content to the tenth of a percent. Test it on the strand CTAGATGCCGTTAGCAGC.

TACGGATGCCstrandpaired strandBase pairs: A with T, C with G
  • a) Write the program. What complement does it display for CTAGATGCCGTTAGCAGC?
  • b) What GC content does it display?
  • c) A classmate writes comp = dna.replace('A', 'T').replace('T', 'A').replace('C', 'G').replace('G', 'C'). What does this line give for ATGC? How many of its four bases are right?
  • d) Without upper() at the input, what does your program display for the strand typed as ctag: which complement, and which GC content?
  • e) In most genes, the reading starts at the start codon ATG, a group of three bases. What does dna.find('ATG') give back for the test strand? How many complete codons does the strand hold from that index on, ATG included?

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

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

Answers

  • a) GATCTACGGCAATCGTCG
  • b) 55.6 %
  • c) AACC; 2 bases
  • d) An empty complement; 0.0 %
  • e) 4; 4 codons

One pass over the strand does both jobs: each base adds its partner at the end of comp, and a G or a C adds 1 to the counter gc. upper() at the input lets the program accept a strand typed in lower case. The program is below.

a)

C gives G, T gives A, A gives T, G gives C: CTAGATGCCGTTAGCAGC becomes GATCTACGGCAATCGTCG, 18 bases, as many as the strand.

Biologists usually write the paired strand in the opposite direction, as the reverse complement; this program gives the complement base by base, aligned with the strand.

b)

The strand has 18 bases, and 10 of them are G or C: C, G, G, C, C, G, G, C, G, C.

10 / 18 × 100 = 55.555..., displayed 55.6 by round(..., 1): GC content: 55.6 %.

c)

ATGC: replace('A', 'T') gives TTGC; replace('T', 'A') then changes every T, the new one included, and gives AAGC; replace('C', 'G') gives AAGG; replace('G', 'C') gives AACC.

The complement is TACG: AACC has the right base at the second and third positions only, 2 bases out of 4. Each replace works on the whole string given back by the one before, so the second call of each pair undoes the first.

Pitfall: chaining replace calls on letters that are exchanged. The loop avoids it, and so do temporary lower-case letters: replace('A', 't'), and so on, then upper().

d)

Without upper(), the bases c, t, a and g match none of the tests base == 'A', base == 'T', base == 'C', base == 'G': the loop adds nothing.

comp stays '' and gc stays 0, so the program displays an empty complement and a GC content of 0.0 %, without any error message. upper() on the first line fixes it.

e)

dna.find('ATG') gives back the index of the first ATG: C, T, A, G sit at the indices 0 to 3, and A, T, G at 4, 5 and 6, so 4.

From index 4, dna[4:] holds 18 - 4 = 14 bases, and 14 // 3 = 4 complete codons: ATG, CCG, TTA and GCA, with GC left over.

Python
dna = input('Strand: ').upper()
comp = ''
gc = 0
for base in dna:
    if base == 'A':
        comp = comp + 'T'
    elif base == 'T':
        comp = comp + 'A'
    elif base == 'C':
        comp = comp + 'G'
        gc = gc + 1
    elif base == 'G':
        comp = comp + 'C'
        gc = gc + 1
print('Complement:', comp)
print('GC content:', round(gc / len(dna) * 100, 1), '%')
StepCallResultstartdnaATGC1replace('A', 'T')TTGC2replace('T', 'A')AAGC3replace('C', 'G')AAGG4replace('G', 'C')AACCEach replace works on the result of the one before
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-strings-built-in-subprograms. 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: indices, slices and the reading of a call come back in every later unit of the course.

Site by Studio Squalli