You are on page 1of 39

TM112: Introduction to Computing and

Information Technology 2

Meeting #4
Block 1 (Part 2)
Introduction to problem solving in Python
OU Materials, PPT prepared by Dr. Khaled Suwais

Edited by Dr. Ahmad Mikati


1
Contents

• Introduction
• Strategies for success
• Strategies for problem solving
• 2.1 Problem solving using decomposition
• 2.2 Iteration
• 2.3 Problems
• 2.4 Using lists for flexibility
• 2.5 Nested iteration
• Summary

2
Introduction
• Programming is about solving problems, so while it is
sometimes perceived as difficult, it is closely related to
many things we do every day.
• Python is a great language for beginner programmers as
small programs can be quickly and easily written.
• In this module, programming is viewed as a problem-
solving process that requires you to think about a
problem and decompose it, before writing any code.

3
Strategies for problem solving

• Often when solving a problem, we can adapt a solution to


one solved earlier.
• This ability to reuse solutions is key. It means that, while
we all start as novice programmers, if we keep going, we
can fully expect to end up tackling complex problems.
• When we are writing a program, we are producing an
algorithm.

4
Problem solving using decomposition
(Algorithms)

• Solving problems, when programming, starts with


working out an algorithm.
• An algorithm tells us or a computer how to carry out a
task.
• An algorithm should be self-contained in that all of the
instructions for the task are included within the algorithm
and nothing else is needed.
• A step-by-step approach allows anyone following the
algorithm to organise their work and know precisely
where they are in the algorithm.
5
Problem solving using decomposition
(Algorithms)

• Most of the algorithms we meet in everyday life – such as


recipes or instructions for completing a task – are
sequences of individual actions.
• We start at the first action (usually at the top, and
sometimes labelled 1 or a) and work through the actions
in order.
•A key point about sequences is that the outcome of
performing an action is dependent on the outcome of
previous steps.

6
Problem solving using decomposition
(Make life simple: algorithms in simple English)

We will describe an algorithm using a series of steps


expressed largely in ordinary natural language, but in a
structured way.
• We solve a problem by decomposing (dividing) it into
steps that solve it.
• If the original problem is complex enough, we may first
decompose it into sub-problems and then decompose
these into steps.
• For difficult problems, we may further decompose the
sub-problems.
7
Problem solving using decomposition
Programming and robotic turtles

• We have seen how to produce an algorithm by


decomposing a problem. How does this relate to writing a
program? Quite simply, we need to keep decomposing
until the steps of our algorithm are simple enough to
translate into single lines of a programming language.
• In this module, the language we are using is Python, and
we will introduce appropriate parts of the language as
needed.

8
Problem solving using decomposition
Programming and robotic turtles

• We have seen how to produce an algorithm by


decomposing a problem. How does this relate to writing a
program? Quite simply, we need to keep decomposing
until the steps of our algorithm are simple enough to
translate into single lines of a programming language.
• In this module, the language we are using is Python, and
we will introduce appropriate parts of the language as
needed.

9
Problem solving using decomposition
Programming and robotic turtles

• In this subsection, we will program a robotic turtle.


• This is a turtle that can be instructed to move around a
two-dimensional space, leaving a trace of its movement
using a coloured pen.
• This provides a lot of opportunities for drawing
interesting shapes, diagrams and indeed pictures.

10
Problem solving using decomposition
Programming and robotic turtles

• Here is our first simple turtle program. (You can try these
commands in Python and see what happens.)
# Draw start of staircase
from turtle import * Comment “no execution“
forward(40)
left(90) the line is stating that we will be
forward(40) working with commands that
right(90) apply to a turtle
forward(40)
The operation that have been
available for us to use on turtle

forward(40) : The operation actually works in terms of pixels. The turtle


always starts pointing horizontally to the right (by default in the middle of
the window), so this line results in the turtle drawing a horizontal line11from
left to right of length 40 units.
Problem solving using decomposition
Programming and robotic turtles

• So the program draws the start of a


staircase consisting of three lines.
• Note that the figure includes an
arrowhead representing the turtle.
• While in general we might want to
hide this, and Python hides the
turtle using ht(), for our purposes it
is sometimes useful to see where
the turtle is and where it is
pointing. This is partly because
some of our solutions will be used
as part of larger solutions.
12
Problem solving using decomposition
Programming and robotic turtles

• If we had written the solution to the previous problem in natural


language (English, in our case), we might have had something
like:
> Draw start of staircase
move forward by 40 units
turn left by 90 degrees

• Our first line uses a ‘>’ symbol, which shows that the first line is a
heading: ‘> Draw start of staircase’, which tells us what we want
to do. It describes the problem we are solving.
• The next two lines are a decomposition of the heading line
above. These two lines achieve the task set out in the heading. 13
Problem solving using decomposition
Drawing some simple shapes through decomposition

Natural Language Python

14
Problem solving using decomposition
Iteration

• Imagine I have decided that I need to walk 10 000 steps


per day to stay fit. I want to know that I have walked 10
000 steps, and I decide I will be more likely to do this if I
have an algorithm to follow.
• I start to write the algorithm:

Having realized that writing the


algorithm out this way is going to
be very tedious, I want a way of
writing down something that
repeats a number of times.
15
Problem solving using decomposition
Iteration

• We will have a variable called ‘step-counter’, and we


need a way of giving it a value, doing something, and
increasing the value. We also need to stop after 10 000.
• We will use the keyword ‘for’ to show that we want to do
something for a number of times. We will use it as
follows:
• This is an example of iteration:
something gets carried out a
number of times (Loop).
• The idea is that we do
something repeating it a
number of times.
16
Problem solving using decomposition
(Making choices)
Now, suppose that I want to click my fingers only when a
multiple of 10 is reached. Then, I can modify my algorithm as
follows:

• Notice that the if keyword is indented at the same level as ‘Walk a


step’ – since they are two parts of the same sequence. The click step
is indented further, to show it is conditional on the condition
expressed by the if statement.
17
Problem solving using decomposition
(Programming for repetition)
In this case, for denotes iterating (looping) around a statement or sequence of
statements.

Python

• The program will move the turtle forward by 100 units. It does this by
moving forward 10 units, and repeating this movement ten times.
• range(1, 11) means that the range of numbers starts at 1, counts
upwards by 1 and stops just before 11.

18
Problem solving using decomposition
(Programming for repetition)

Python
Alternative Solution

• Recall that In Python, when we specify a range using just one


number, then the range starts at 0.
• In this case, when using range(10), we get a range of whole numbers
from 0 to 9.

19
Problem solving using decomposition
(A more powerful approach to design)
• Let’s think about a slightly more complicated problem.
We will design and implement a program to draw two
squares, one below the other, with a gap in between.

Problem decomposition 20
Problem solving using decomposition
(A more powerful approach to design)

• We have now decomposed the problem into sub-


problems, rather than steps.

The symbol >> refers to sub-problems


21
Problem solving using decomposition
(A more powerful approach to design)

• Now we can decompose


sub-problems into steps.
• We did copy and paste
from the original square
algorithm! This is know as
reusing solutions.
• Reuse is a mature approach
to program design for
saving time, and avoid
introducing errors
22
Using lists for flexibility
(Drawing a graph of a fixed number of points)
• In this subsection, we will consider how to draw a line graph.
• We will assume we are plotting the sales of gloves, by a given
company, over the four quarters of the year.
• Now, we have seen how a variable could be used to control a
loop, and that it is essentially a named box that can hold a value.
• Here we will use variables to hold the sales of gloves for each
quarter.
• Variables gloves1, gloves2, gloves3 and gloves4 to hold the
number, in millions, of gloves sold in the first, second, third and
fourth quarters.
• When working with variables, we need to be able to give them
values. Python has, like many programming languages, a
23
construct called assignment.
Using lists for flexibility
(Drawing a graph of a fixed number of points)
• The turtle has considerably more operations than we
have seen so far.
In particular, it has an operation goto that allows us to move the
pen to a position, drawing a line as we go.

• Assume we are starting at position (0,0), the python


code goto(40,0) moves the turtle horizontally to
position (40,0), drawing a line if the pen is down. The
first value in the brackets represents the horizontal
displacement (from 0) and the second value represents
the vertical displacement.
24
Using lists for flexibility
(Drawing a graph of a fixed number of points)

Python
# Produce graph for gloves sales
from turtle import *
# set up the variables
g1=10
g2=8
# produce the x axis
goto(40,0)
goto(0,0)
# produce the y axis
goto(0,100)
goto(0,0)
# Plot data
goto(20, g1*10)
goto(40, g2*10)
ht() # to hide the turtle prompt
25
Using lists for flexibility
(Drawing a graph of a fixed number of points)
Python
# Produce graph for gloves sales
from turtle import *
# set up the variables
clear()
pu()
setpos(0,0)
pd()
g1=10
g2=8
# produce the x axis
goto(40,0)
goto(0,0)
# produce the y axis
goto(0,120)
goto(0,0)
# Plot data
goto(20, g1*10)
dot( 5, "blue")
write("g1", False,"center","bold")
goto(40, g2*10)
dot( 5, "red")
26
write("g1", False,“left","bold")
ht() # to hide the turtle prompt
Using lists for flexibility
(Working with simple lists)

• Now you may have noticed that in the last section we


were doing something repeatedly, but we didn’t use a
loop.
• We needed to plot a number of points, but each point
required us to use a different variable.
• Let’s think about our gloves data. Imagine we want to
know the total sales of gloves for the year.
total = gloves1 + gloves2 + gloves3 + gloves4

27
Using lists for flexibility
(Working with simple lists)

• A list is a data structure in Python that is a mutable


(or changeable), ordered sequence of elements.
• Each element or value that is inside of a list is called an item.
• Lists are defined by having values between square brackets [ ].
• Lists are great to use when you want to work with many
related values.
• They enable you to keep data together that belongs together,
condense your code, and perform the same methods and
operations on multiple values at once.

28
Using lists for flexibility
(Working with simple lists)

• To create a list we use square brackets to indicate the start and end of
the list, and separate the items by commas:
L = [1,2,3]
• You can use the print function to print the entire contents of a list:
print(L) #[1, 2, 3] will be printed

• Lists are mutable: individual elements can be reassigned in place.


L[0] = 4
print(L) #[4, 2, 3] will be printed

• The empty list is []. It is the list equivalent of 0 or empty string ''.
• If you have a long list to enter, you can split it across several lines, like below:
nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32,
33, 34, 35, 36, 37, 38, 39, 40]

29
Using lists for flexibility
(Working with simple lists)

• If we had sales data for every day of the year, with


gloves1 holding the data for the first day of the year,
and so on, we could still use the previous approach –
but things become tedious.
• Instead, we would like a way of holding the glove data
together and being able to access it in a flexible way.
• In Python, we can say:
gloves = [10,8,3,5]
• This variable refers to a list of numbers, rather than just
a single number as earlier.
30
Using lists for flexibility
(Working with simple lists)
Now, to calculate and print the total number of glove
sales :
gloves = [10,8,3,5]
total = 0
for index in range(0, len(gloves)):
total = total + gloves [index]
print(total)
This gives me a loop which gets executed with values for
index of 0, 1, 2, and 3.

31
Nested iteration
(Independent nested loops)
• Sometimes we use loops within loops (embedded loops) to solve
more complex problems.

• For example, what if we had monthly sales data of gloves for several
years and wanted to calculate the total sales for each year? In this
case, we might have a list containing a list for each year.

• Consider the problem of producing a ‘times table’: a table showing


all the possible multiplications of two numbers between 1 and 12, in
order.

• Breaking the problem down, we see the need to show all the
multiples of 1, all the multiples of 2, and so on. So we can use a loop.
The sub-problems, such as finding the multiples of 1, 2 and 3, can
also be done using a loop. 32
Nested iteration
(Independent nested loops)
Problem
Decomposition

# Produce times table


size=12
for row in range(1, size+1):
for column in range(1, size+1):
print(row*column, end=' ')
# Move to a new line
print()

Translated
Python Code 33
Nested iteration
(Independent nested loops)

• In the previous case, we just want a space character between the


numbers. We need to include end = ... any time we don’t want print
to move to a new line. So end = ' ' adds a space character without
moving to a new line.
• To prevent print moving to a new line, but without adding a
character, we can say end = ''.

34
Nested iteration
(Programming the turtle using nested loops)

• Consider a program to produce a number of squares across


the page. A decomposition of this problem is as follows:

• If we now copy the


decomposition from
subsection 2.2.3 for ‘Draw a
square’ into the above
decomposition, we get:
35
Nested iteration
(Independent nested loops)

Problem
Decomposition

# Draw squares across page


from turtle import *
number_of_shapes=4
for shape in range (1, number_of_shapes +1):
for shapes in range(1,5):
forward(40)
right(90)
# Move forward to start position of next square
pu()
forward(50) Translated 36

pd()
Python Code
Nested iteration
(Dependencies between nested loops)

• In this subsection, we will look at loops where the index of


the inner loop is dependent on the outer loop.

• Consider if we wanted to print a triangle, not using the


turtle robot, but as a block of characters – for example, the
following right-angled triangle:

*
**
***

37
Nested iteration
(Dependencies between nested loops)

Python
# Print Right-angled triangle
size=3
for line in range(1,size+1):
for asterisk in range(1, line+1):
print('*', end='')
print()

38
Summary
After studying this part, you should be able to:
• decompose a simple problem to produce an algorithm,
using sequence, selection and iteration
• translate a simple design of an algorithm into Python
• make use of iteration to produce code that can solve
problems where we need to do things several times
• make use of lists to express the idea that a number of
data items are related
• solve problems involving drawing line-based images using
turtle graphics
• use algorithmic thinking to solve problems. 39

You might also like