You are on page 1of 32

TM112: Introduction to Computing and

Information Technology 2

Meeting #5
Block 1 (Part 4)
Patterns, algorithms and programs 1
OU Materials, PPT prepared by Dr. Khaled Suwais

Edited by Dr. Ahmad Mikati


1
Contents

• Introduction
• 4.1 Calculate
• 4.2 Document and test
• Lists
• Summary

2
Introduction
• We will study several types of problems and the
corresponding patterns that you can use to solve them.
• A pattern will be a template to be filled in to obtain a
concrete algorithm.
• When given a problem, if you recognise the type of the
problem, you can then use the corresponding pattern to
create a concrete algorithm for the given problem. That is
much easier and faster than having to design an algorithm
from scratch.

3
Introduction
• The problem-solving process you saw in Part 2 becomes more
structured, with intermediate steps to go from problem to
algorithm, illustrated in this Figure.

4
4.1 Calculate
• Throughout this part, we will show you various kinds of
numeric problems,
• i.e. where the inputs and outputs are numbers.

• In this section, we’ll start with the simplest of such


problems, with a single output calculated directly from the
inputs.
• The aims of this section are to recap and summarise some
concepts you already came across in Part 2 and possibly in
TM111, and to set the stage for the structure of the
numeric problems and solutions in the rest of this part.

5
4.1.1 Numeric expressions

• Python can be used as a simple calculator.


• Python provides integers (whole numbers) like –3 and 0 and
123456789. Unlike other programming languages, Python integers
can be arbitrarily large (for both positive and negative integers).
• Note that an integer must be written as a sequence of digits: even for large
numbers, you can’t use commas, full stops, underscores or any other mark to
group digits into thousands.

• Python also provides floating-point numbers (decimal numbers) like


–3.2 and 0.5 and 12345.6789.
• Python has no thousands separator and uses the point as the decimal
mark, so the number one million and a half is written as 1000000.5.
6
4.1.1 Numeric expressions

• Python provides several numeric operators to express


calculations over numbers.
• Besides addition (+), subtraction (-) and multiplication (*),
there are two kinds of divisions.
• A single division sign (/) represents exact division, i.e. the result is
always a floating-point number,
• A double division sign (//) represents floor division, i.e. the result
is always rounded down to an integer.
• For example, 1/2 is 0.5, but 1//2 is 0.

7
4.1.1 Numeric expressions
• Python also provides the remainder (modulus) operator,
confusingly written as the percentage sign (%).
• The % operator calculates the remainder of the floor
division of the first number by the second,
• For example, 7%2 (read as “7 modulo 2”) is 1 because 2 fits 3 times
in 7 (3 * 2 = 6) and 1 remains (7 – 6 = 1).

• The remainder operator is useful to check if a number n is a


multiple of another number m; if it is, then n modulo m will
be 0, because m will fit an exact number of times in n.
• For example, 14%7 is 0 because 14 is a multiple of 7.

8
4.1.2 Formula problems: pattern
Problem 4.1 Brick volume

• Compute the volume of a brick, given its width, length and


height.
• We will systematically follow the problem-solving
workflow in slide 4 and, in the process, introduce the first
problem type and its solution pattern.

9
4.1.2 Formula problems: pattern
Problem 4.1 Brick volume
Decompose the problem

• The first step is to decompose the problem into simpler sub-


problems.
• In this case, we remember from school that usually the
volume of a solid is obtained from the area of its base and its
height. In this problem, the base of the brick is the
rectangular area formed by the width and length.
• Since the volume depends on the area, I have to decompose
the problem in the right order:
• > Compute the volume, given the width, length and height:
• >> Compute the base area, given the width and the length
• >> Compute the volume, given the base area and the height
10
4.1.2 Formula problems: pattern.
Pattern 4.1 Formula
Line Instruction
   
1 initialise the input variables
2 set the output variable to the value of the formula applied to the
inputs
3 print the output variable

• The pattern is not an algorithm: it doesn’t tell us the precise


variables and values to use, because that will depend on the
problem.

• The pattern is a template that needs to be ‘filled in’ to become an


algorithm. Every algorithm thus obtained is a concrete instance of
the abstract pattern. Therefore we will also use the verb
‘instantiate’ to mean ‘fill in’.
11
4.1.2 Formula problems: pattern
4.1.3 Formula problems: algorithm
Instantiate the Pattern
• We have to fill in the pattern twice: once for each sub-
problem.
• The pattern mentions input and output variables.
• In the first sub-problem (computing the area), the inputs are
the width and length and the output is the area.
• In the second sub-problem (computing the volume), the
inputs are the area and the height and the output is the
volume.
• Note how the input of a sub-problem can be the output of a
previous sub-problem.

12
4.1.2 Formula problems: pattern
4.1.3 Formula problems: algorithm

• We can now start to develop the algorithm for the first


sub-problem (computing the area) by filling in the
pattern.
• We are going to fill in the pattern bit by bit, so there will
be several intermediate, partially filled-in versions of the
algorithm.
• We first insert the patterns into the problem
decomposition to ensure I won’t forget to fill in all the
steps.

13
4.1.2 Formula problems: pattern
4.1.3 Formula problems: algorithm

• Line 3 asks to provide the


initial values, but the sub-
problem doesn’t state what
the values of the width and
length are.
• Usually the algorithm
would ask the user to type
in some values on the
keyboard, but to keep
things simple I choose the
values myself – preferably
small ones (let’s say 2 and
3) to easily check if the
area is correct in line 5.
• So, line 3 of algorithm 4.1
version 1 is instantiated as
14
follows:
4.1.2 Formula problems: pattern
4.1.3 Formula problems: algorithm
• Note how line 3 of the pattern
became two lines of the
algorithm.
• Note that we use specific and
descriptive variable names that
capture the problem at hand.

• Next we have to fill in what is


now line 5.
• The output is the area, and the
formula to calculate a
rectangular area is simply the
product of width and length.

• Next, in line 6, we replaced the


output variable with area as per
the variable used in line 5.
15
4.1.2 Formula problems: pattern
4.1.4 Formula problems: program

Implement the algorithm

• The next stage of the problem-solving process is to


translate the algorithm to Python code.

• This is straightforward for formula problems because


they only use assignments, numbers and expressions.

16
4.2 Document and test
• For complicated or less familiar problems, the reader can struggle
to understand what’s going on in the code, even with descriptive
variable names.

• The solution is to document the code, by adding comments.

• Comments should be used to explain the inputs and outputs, in


what units the values are, and any constraints – for example, not
being negative.

• Simple and familiar formulas don’t require explanation.

17
4.2 Document and test
• No matter how simple your program is, you should get
into the habit of testing it to catch any errors.

Testing a program consists of writing down several pairs


of inputs and the corresponding expected outputs, running
the program for those inputs, and checking whether the
actual outputs match the ones you expected.

18
4.2 Document and test
• You only have to test your program for admissible input
values and document in the code which values are not.
• If the user inputs an inadmissible value, it’s their fault, and
all bets are off: your program may crash, output a
nonsensical value – or, even worse, output a value that
seems correct.
• For numeric problems, some of the typical conditions for
an input value to be admissible are: the value is an integer;
positive; negative; non-zero; a multiple of some number n;
a percentage (i.e. a floating-point number from 0 to 1 or
an integer from 0 to 100); larger than another input; etc.
19
How to solve computational problems-
Summary
As a conclusion, we briefly summarize a process to solve
computational problems:

The process consists of:


1- Decomposing the problem into sub-problems.
2- Recognising the type of each sub-problem, and instantiating the
corresponding solution pattern to obtain an algorithm for each sub-problem.
3- Putting the algorithms together to solve the overall problem.
4- Translating the overall algorithm to Python code.

Finally , programmers are urged to document and test where necessary.

20
Lists

• Lists are written as comma-separated items (also called the


elements of the list) within square brackets. The empty list,
without any elements, is simply written as [].
• An example of a list with three integers is [4, 2, -9].
Lists can be assigned to variables, e.g. temperatures =
[4, 2, -9]. The variable name should reflect the content
of the list to make the program easier to understand.
The length of a list is its number of elements.

The Python expression


len(temperatures) computes the length of temperatures
– in this case, 3.
21
Lists

• There are a number of things which work the same way for lists as for
strings.
• len(): where you can use len(L) to know the number of items in
a list L.
• in: operator which tells you if a list contains something.
• Examples:
if 2 in L:
print('Your list contains number 2.')
if 0 not in L:
print('Your list has no zeroes.')

22
Lists
• A list is a data structure in Python that is a mutable
(or changeable), ordered sequence of elements.

23
Lists

• A list can contain all kinds of things, even other lists.


• For example, this is a valid list:
L = [1, 2.718, ‘xyz’, [1,2,5]]

• To access the items of the list inside a list, you have to use double squared
brackets.

24
Lists

• Indexing and slicing work exactly as with strings:


L[0] is the first item of the list L.
L[:3] gives the first three items.
• The + operator adds one list to the end of another.
• The * operator repeats a list.
• Following are some examples.

25
Lists

In Python, for loop is used to iterate over the items of any sequence
including the Python list, string, tuple etc. The for loop is also used to access
elements from a container (for example list, string, tuple) using built-in
function range().

Both of the following examples print out the items of a list, one-by-one, on
separate lines.

26
Lists

27
Lists

28
Lists
More operations on lists:
• Concatenation:
>>> L1 = [0,1,2]; L2 = [3,4,5]
>>> L1+L2
[0,1,2,3,4,5]
• Repetition:
>>> L1*3
[0,1,2,0,1,2,0,1,2]
• Appending:
>>> L1.append(10)
[0,1,2,10]
• Sorting:
>>> L3 = [2,1,4,3]
>>> L3.sort()
[1,2,3,4] 29
Lists
• Reversal:
>>> L4 = [4,3,2,1]
>>> L4.reverse()
>>> L4
[1,2,3,4]
• Shrinking:
>>> del L4[0] # L4 will be [2,3,4]
>>> L4 = [] # L4 will be []
• Index and slice assignment:
>>> L1 = [10,20,30,40]
>>> L1[1] = 0 # L1 will be [10,0,30,40]
>>> L1[1:4] = [4,5,6] # L1 will be [10,4,5,6]
• Making a list of integers:
>>> list(range(4))
[0,1,2,3]
>>> list(range(1,5))
[1,2,3,4]
30
Example- List of lists
• Suppose we have the following list:
List=[['Ali', 5, 10,15],['Naji',12,12,15],['Fadi',10,14,12],['Rajaa',18,16,14]]
- Print the average of the second grade for all students.
- Print the name of the student and his/her average grade

Accessing the 2nd grade

OR

31
Summary
In this part, you learned further techniques to solve
computational problems by:
• looking in the problem statement for the input(s) and the
output(s)
• thinking about which inputs are not allowed, e.g. negative
numbers
• writing tests (pairs of admissible inputs and their
expected outputs)
• recognising the type of the problem or the types of the
sub-problems
• instantiating the patterns for those problem types
• combining the algorithms for the sub-problems to solve
the whole problem. 32

You might also like