ANSWERS TO EXERCISES
CHAPTER 1
EXERCISE 1
List the core concepts of CT:
- logical thinking;
- algorithmic thinking;
- decomposition;
- generalisation and pattern recognition;
- modelling;
- abstraction;
- evaluation.
EXERCISE 2
Give an example of how you think people in each of the following occupations think computationally:
- mathematician: evaluates logical statements, carries out long chains of processes such as long division, abstracts values to variables;
- scientist: uses logic to reason about cause and effect, decomposes hierarchical relationships between species, follows experimental procedure, models phenomena such as climate dynamics;
- engineer: writes assembly instructions, decomposes construction into a series of tasks, creates models of artefacts, evaluates competing solutions to a problem;
- linguist: identifies patterns in grammar, models evolution of words in human history.
CHAPTER 2
EXERCISE 1
Mark the following statements as true or false:
- An inductive logical argument makes conclusions that are probable rather than certain. True.
- So long as a deductive argument has true premises, then its conclusion is certain. False – the conclusion must also necessarily follow from the premises.
- In Boolean logic, a logical expression can have a maximum of two propositions. False – an expression can have many propositions, but each proposition can have only one of two possible values.
- Logical AND has a higher precedence than logical OR. True.
- x = x + 1 would be a valid expression in an algorithm. True.
EXERCISE 2
Consider the following search terms and decide which recipes will be returned:
- cooking time less than 20 minutes and not vegetarian: Garlic dip ;
- includes chicken or turkey but not garlic: Broiled chicken salad ;
- doesn’t include nuts: Broiled chicken salad, Three-spice chicken .
EXERCISE 3
Express these rules of thumb as logical statements. Each statement should make a conclusion about the estimated queuing time:
- if customer is carrying items by hand, then time is 1 minute;
- if customer is carrying a basket, then time is 2 minutes;
-
if customer is pushing a trolley, then:
- if trolley is half-full, then time is 5 minutes;
- if trolley is full, then time is 10 minutes.
- if customer is at a self-service checkout, reduce time by 80 per cent.
EXERCISE 4
Take the logical statements from the previous question and incorporate them into an algorithm. The algorithm should take a queue as input, and should output the total estimated queueing time.
EXERCISE 5
Based on the algorithm for singing 99 Bottles of Beer write a pseudocode algorithm for singing The 12 Days of Christmas .
CHAPTER 3
EXERCISE 1
Mark the following statements as true or false:
- Your goal defines how the problem should be solved, not what needs to be done. False.
- It is inadvisable to begin writing a solution before the goal is defined. True.
- For any non-trivial problem, there is likely only one solution. False.
- Decomposition guarantees an optimal solution. False.
- A tree structure is hierarchical in nature. True.
- All nodes in a tree structure have one or more child nodes. False .
- Patterns among separate groups of instructions can be generalised into subroutines. True.
EXERCISE 2
You’re planning to hold a birthday picnic for a child and her friends. Break down the preparation into a tree structure of tasks.
Figure B.1 Task breakdown for picnic
EXERCISE 3
Update the drawing of the smiley face discussed earlier in the chapter so that the positioning of the features (eyes and mouth) are calculated automatically based on the positioning of the face.
-
‘Draw face’ is a subroutine (r, x, y):
- Draw circle with radius r at position x,y filled yellow
- Call ‘draw eye’ with parameters r1 = 0.25 × r, r2 = 0.125 × r, x = x -0.5 × r, y = y -0.5 × r
- Call ‘draw eye’ with parameters r1 = 0.25 × r, r2 = 0.125 × r, x = x + 0.5 × r, y = y -0.5 × r
- Call ‘draw mouth’ with parameters x1 = x -0.5 × r, y1 = y + 0.5 × r, x2 = x + 0.5 × r, y2 = y + 0.5 × r
EXERCISE 4
Further update the drawing of the smiley face.
-
i. ‘Draw face’ is a subroutine (r, x, y):
Draw circle with radius r at position x,y filled yellow
ii. ‘Draw mouth’ is a subroutine (x1, y1, x2, y2):
Draw line from x1,y1 to x2,y2 coloured red
iii. ‘‘Draw eye’ is a subroutine (r1, r2, x, y):
Draw circle with radius r1 at position x,y
Draw circle with radius r2 at position x,y filled brown -
‘Draw scar’ is a subroutine (x,y):
Draw line from x,y to x,y+10
Draw line from x-2,y+2 to x+2,y+2
Draw line from x-2,y+4 to x+2,y+4
Draw line from x-2,y+6 to x+2,y+6
Draw line from x-2,y+8 to x+2,y+8 -
‘Draw nose’ is a subroutine (r, x, y):
Draw circle with radius r at position x,y filled red
Drawing the nose must be done after drawing the face and eyes for it to appear above them.
EXERCISE 5
Use your tree structures to guide your questioning strategy. Which one of the three structures would minimise the number of questions you would have to ask? Try dividing groupings into sub-groupings to see if that helps to reduce the number of questions.
Figure B.2 Species organised into a tree structure by number of legs
The tree helps to show the maximum number of questions you would have to ask when following each strategy. For example, when following the ‘number of legs’ strategy, the maximum numbers of questions you would ask is eight:
- Does it have no legs? No.
- Does it have 4 legs? No.
- Does it have 2 legs? Yes.
- Is it a bat? No.
- Is it a human? No.
- Is it a penguin? No.
- Is it an ostrich? No.
- Is it a swan? Yes.
Compare this to the other strategies.
The ‘does it fly?’ strategy is potentially good because the tree is very unbalanced – you could eliminate a huge number of animals if the answer to ‘Does it fly?’ is ‘yes’. However, this is also its weakness. If the answer is ‘no’, you could potentially have to ask eight more questions, meaning the maximum number of questions for this strategy is nine.
The ‘species’ strategy provides a balanced and shallow tree. The maximum number of questions you would have to ask is seven.
Figure B.3 Species organised into a tree structure by ability to fly
You can combine strategies by asking a different question after you’ve descended one level in the tree. However, you must be careful which one you pick. If you find out the animal is a mammal, it would be sensible to ask how many legs it has because mammals vary in number of legs. If you find out the animal is a fish, the ‘number of legs’ strategy is useless because fish are generally legless.
Figure B.4 Species organised into a tree structure by biological class
CHAPTER 4
EXERCISE 1
Mark the following statements as true or false:
- An abstraction leaks when it takes details into account unnecessarily. False.
- An abstraction must be instantiated before it can be executed. True.
- A dynamic model shows the changes in state of something over time. True.
- A directed graph is a dynamic model. False.
- Accuracy describes closeness to the true value; precision describes the level of refinement in a measurement. True.
EXERCISE 2
Order the following into layers of abstraction, starting with the most general and ending with the most specific:
- animal;
- bird;
- penguin;
- Emperor penguin;
- Tommy the Penguin.
EXERCISE 3
For renting out a car, which of the following is it necessary for a rental company to know about?
- The car’s current mileage. Yes: the distance travelled by the customer could be used to calculate the price .
- The customer’s height. No. Irrelevant to a car rental.
- Number of wheels on the car. No. This is both constant and irrelevant to a car rental (if the number of wheels on the car has changed, something has gone very wrong!).
- The car’s current fuel level. Yes: the car needs handing over to the customer with a specific amount of fuel.
- ID number of the customer’s motorcycle licence. No. A motorcycle licence isn’t required to rent a car.
EXERCISE 4
Model all the possible stages of an order using a state machine diagram.
Figure B.5 State machine diagram showing states of an order
EXERCISE 5
Extend the diagram so that the data structure records the student’s grades.
Figure B.6 Extended data model of a student’s record
CHAPTER 5
EXERCISE 1
Mark the following statements as true or false:
- Errors can result from statements that are grammatically valid. True.
- The exit condition of a loop is evaluated after each statement inside the loop is executed. False.
- Defensive programming assumes that code is safe until proven otherwise. False.
- Bottom-up testing is an effective way of finding design flaws. False.
- An equivalence class groups all inputs to an algorithm that elicit the same type of response. True.
EXERCISE 2
Explain the difference between a bug and an error.
A bug is fault in a solution that can cause erroneous behaviour. An error is behaviour observed when executing a solution which does not match with expected behaviour.
EXERCISE 3
An ‘if–then’ conditional tells the computer to carry out some instructions if a certain condition is met. How could you modify this form to carry out instructions if the condition is not met?
The if–then–else form provides the means for adding instructions when a condition is not met. Instructions to be executed if a condition is not met go in the else part.
EXERCISE 4
The algorithm in the Minesweeper example ( Figure 5.2 ) contains an error. Find it and fix it.
The condition that decides whether to repeat the loop checks if n is less than 8. That means execution of the loop ends as soon as n becomes 8, meaning the last square doesn’t get checked. If a mine were in this square, it would be missed.
EXERCISE 5
Write an algorithm for the FizzBuzz game that analyses an input number and returns the correct response.
CHAPTER 6
EXERCISE 1
Mark the following statements as true or false:
- Most real-world software solutions are shown be correct empirically rather than mathematically. True.
- Reducing the number of failing tests doesn’t strengthen your claim to a solution’s correctness. True.
- An inefficient solution cannot be considered correct. False.
- An elegant solution maximises both effectiveness and simplicity at the same time. True.
- A usability evaluation begins by explaining to the test subject how to use the system. False.
EXERCISE 2
Write generic versions of both the obvious solution and Gauss’s solution, both of which sum up numbers from 1 to N .
Obvious solution:
Gauss’s solution:
EXERCISE 3
Which one of these two algorithms is more efficient in terms of time complexity?
Gauss’s solution, despite having more statements in it, is still more efficient than the obvious solution because it takes a fixed number of steps to process any range (in other words, its time complexity is constant). The obvious solution still has linear time complexity, so the time it takes to execute grows as the range of numbers grows.
EXERCISE 4
Can you see how the data could be made to take up less space?
Sometimes the end of one line describes the same colour as the beginning of the next line. For example, the end of first line is ‘5W’ and the beginning of the second is ‘3W’. We could reduce the space they consume by 50 per cent by combining them both into ‘8W’.
EXERCISE 5
What are the names of the five components of usability and what do they measure?
- Learnability: measures how easy users find accomplishing basic tasks using the solution for the first time.
- Efficiency: how quickly users can perform tasks, once they have learned the solution.
- Memorability: how easily users can re-establish proficiency when they return to the solution after a period of not using it.
- Errors: how many errors users make, how severe these errors are and how easily users can recover from them.
- Satisfaction: how pleasant the design is to use.
CHAPTER 7
EXERCISE 1
Write a program that creates two variables, r and pi .
pi = 3.142
r = 5
EXERCISE 2
Use the variables from the previous question to create a third variable called area which holds the area of a circle with radius r .
area = pi * r * r
EXERCISE 3
Write a program that creates two number variables, a and b , and uses the print command to output True or False depending on whether or not a is greater than b .
a = 4
b = 5
print(a > b)
EXERCISE 4
Take the code from the previous answer and write a function called bigger .
CHAPTER 8
EXERCISE 1
Mark the following statements as true or false:
- You cannot assign the value of an immutable variable to another variable. False.
- The continue keyword forces a loop to end immediately and continue executing with the code that follows the loop. False.
- Declarative programming is useful when you need careful control over the step-by-step behaviour of a program. False.
- Only one part of a multi-part if-statement can be executed at the most. True.
- An expression is a piece of code that evaluates to a result. True.
EXERCISE 2
Rewrite the code so that notes_1 can be updated without simultaneously altering the value of notes_2 .
notes_1 = [‘Do’, ‘Re’, ‘Me’]
notes_2 = notes_1 + [‘Fa’]
print(notes_2)
EXERCISE 3
Take your solution to Chapter 2 , Exercise 5 (write an algorithm for singing The 12 Days of Christmas ). Convert the algorithm into a Python program.
EXERCISE 4
Write a program that takes a list of Fahrenheit measurements and converts it into a list of Celsius measurements.
fahrenheit = [0, 10, 20, 30, 40, 50 , 60, 70, 80, 90, 10]
celsius = [(f-32) * (5 /9) for f in fahrenheit]
EXERCISE 5
Using the filter function, write a program to filter out annoying words from a list of words, specifically words that are in all upper-case characters and words that end with multiple exclamation marks.
CHAPTER 9
EXERCISE 1
Mark the following statements as true or false:
- Global variables are the preferred way to pass information between functions. False.
- When functions know too much about other functions’ workings, altering them risks causing side effects. True.
- Objects defined inside a function cannot be referenced outside that function. True .
- A module takes its name from the file it’s defined in. True.
- Files in a Python package may only have names made up of letters or numbers. False.
EXERCISE 2
What is the output of the program?
No, print this!
Print this message.
EXERCISE 3
Try running the program, and explain why it results in an error.
The first line of my_function tries to print the value of s , but s hasn’t been defined yet. If you wanted to access the global s , you would need first to add the statement ‘ global s ’, to make it explicit that you want to use the global variable. The code in Exercise 2 didn’t use the global s , instead it defined a local variable (which just happened to have the same name).
EXERCISE 4
Extend the program.
CHAPTER 10
EXERCISE 1
Mark the following statements as true or false:
- All items in a Python list must have the same type. False.
- Creating a new object of a certain class is called instantiation. True.
- A subclass must override all the methods it inherits from the parent class. False.
- Reusing patterns helps to reduce effort when coming up with solutions. True.
- Design patterns are typically categorised into the following three categories: creational, structural and atypical. False.
EXERCISE 2
Write a Python program that prints out all the unique words in a sentence.
sentence = ‘If I bake this bitter butter it would make my batter bitter but a bit of better butter would make my batter better’
unique_words = set(sentence.split(‘ ‘))
EXERCISE 3
Write an insult generator in Python that picks a random assortment of adjectives and orders them correctly in an insulting sentence.
EXERCISE 4
Define a class for each of the three shapes: Rock , Paper , Scissors.
EXERCISE 5
Add a class to act as a computer player.
EXERCISE 6
Add code to play one round of the game.
CHAPTER 11
EXERCISE 1
Mark the following statements as true or false:
- Static models show how entities change over time. False.
- The middle section of a class in a class diagram lists attributes. True .
- Inheritance is modelled using an arrow with a solid, white arrowhead. True.
- Aggregation and composition are types of dependency. False.
- A state machine diagram emphasises the changes in state of a single object. True.
EXERCISE 2
Look at Figure 11.13 . Extend the diagram to include chess pieces.
Figure B.7 Class diagram of a chess set
EXERCISE 3
Draw a use case diagram for a typical, high street cash machine.
Figure B.8 Use case diagram of a typical cash machine
EXERCISE 4
Draw an activity diagram for the process of withdrawing money from a cash machine.
Figure B.9 Activity diagram for cash withdrawal
EXERCISE 5
There have been complaints about the card-operated turnstile gate (section ‘Workflows’). Some people forget their card and leave it in the slot. Alter the activity diagram so that this can no longer happen.
You could alter the diagram so that the actions ‘System ejects card’ and ‘System unlocks turnstile’ are no longer done in parallel. Instead, make them linear so that unlocking the turnstile happens after the card is ejected. Add an activity between them called ‘user takes card’, so that the turnstile won’t unlock until it detects that the user has retrieved their card.
CHAPTER 12
EXERCISE 1
Mark the following statements as true or false:
- A syntax error will not be reported until the line containing it is executed. False.
- Code in a finally block is always executed after the code in its corresponding try block. True.
- Validation determines whether or not a solution actually solves the original problem. True.
- The setUp function in a Python unit test is executed once before each individual test function. True.
- By default, Python prints log messages to a file called log.txt . False.
EXERCISE 2
Turn your FizzBuzz algorithm into a Python program.
EXERCISE 3
Write a unit test for your FizzBuzz program.
To make the code testable we reorganise the routine into a function that can be called. We also add the check for non-numeric input.
The test case for this code is as follows:
EXERCISE 4
Try the program out and, using a debugger and/or log messages, find and fix the problems.
Some bugs:
- The while loop condition should loop if the input is not ‘0’.
- for letter in range(1, len(word)): This line is wrong because it misses the first (i.e. zeroth) letter of the word. It should be for letter in range(0, len(word)):
- if output != word: should read if output == word: