cmpt141-ch01 Solutions
cmpt141-ch01 Solutions
Algorithms
Reading Roundup
"Reading Roundup" slides feature questions whose answers can be found in the pre-class readings.
What is an algorithm?
What is the difference between a problem and an algorithm?
What is abstraction?
Exercise 1
Write algorithms in pseudocode for the following problems:
Answers for developing algorithms may vary wildly. The following are just examples of simple algo-
rithms.
1
Example: Mailing a letter
Here’s one possible answer:
(a) Put letter in envelope
(b) Write address on envelope
(c) Attach stamp to envelope
(d) Seal envelope
(e) Go to mailbox and drop off envelope
2
Answer:
(a) Walk to mailbox
(b) Grab handle to open mailbox
(c) Insert envelope into open slot
Computing an Average
Demo 1
Translate the following pseudocode into Python:
Algorithm Average :
Input : a set of numbers
let total = 0;
for each number x in the set of numbers :
let total = total + x
let average = total / size of the set of numbers
Solution
def Average ( S ):
# you should be able to see that this code here
# looks a lot like the pseudocode algorithm
total = 0
for x in S :
total = total + x
average = total / len ( S )
return average
The point here is not to understand why the Python program looks the way it does, but to be able to see
which lines in the pseudocode algorithm become which lines in the Python code, which is something
3
you should be able to appreciate at this point. Parts of this program look a lot like the pseudocode
algorithm, but, unlike the pseudocode, everything written in the Python program has a strictly defined,
unambiguous meaning.
The green lines are called "comments" and are not actually part of the computer program. All text after
a # character on a line is ignored by Python and is only used to describe what the program is doing.
3 Levels of Thought
meanings of terms.