Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 36

TM112: Introduction to Computing and

Information Technology 2

Meeting #6
Block 2 (Part 2)
Patterns, Algorithms and Programs 2

Block 2 (Part 4)
Organizing Your Python Code and Data
OU Materials, PPT prepared by Dr. Khaled Suwais

Edited by Dr. Ahmad Mikati 1


Contents

• Introduction
• Generate a List- Append
• Reduce
• Search
• Combine
• The Final Problem
• Summary

2
Introduction
• This part continues to apply the problem-solving approach from Block 1
Part 4, in which we go from problems to programs via patterns and
algorithms.

• Block 1 Part 4 ended with the generation of a sequence of numbers. To


be able to better process sequences of numbers, they will be stored in
lists.

• Lists are a very useful and flexible way of storing multiple data items.
Most Python programs use lists. In this part, I will show some common
problem types on lists and the corresponding solution patterns.

• As part of the overall problem-solving process, this part will also


continue to emphasize the importance of documenting and testing
your programs.

3
• Generate a List

• Sequences and Lists


• Append
• Filter
• Transform

4
Append
• Normally the generated sequence has to be stored for
further processing, and lists are ideally suited for that.
Storing the generated sequence in a list requires just two
changes to Pattern 2.1:
 start with the empty list.
 instead of (or in addition to) printing the value,
append it to the list, i.e. add it to the end of the list.

• By appending each value, the list will store the values in


the same order as they were generated.

5
Append
• In Python, adding value to the end of a list , say sequence, is
intuitively written as:

sequence = sequence + [value]


Note the square brackets around the value. That tells Python to concatenate
(‘add’ together) two lists, the second of which happens to have one element in this
case. Forgetting the brackets will lead to an error.

or
sequence.append(value)

6
Filter

• Often lists are not generated from scratch


but from an existing list. One common way is
to ‘filter’ the existing list: generate a new list
that only includes those values of the input
list that satisfy some condition.

7
Python editor: hot days program
• Given a list of daily temperatures in degrees Celsius in a certain place,
construct a list of the temperatures above 30. Assume temperatures are
given as whole numbers.

# Problem: obtain the temperatures above a threshold


# Input: a possibly empty list of temperatures in Celsius
daily_temperatures = [28, 33, 29, 32, 27,42,29,36]
# Output: the list of temperatures above 30
hot_days = [] # a new list that will contain the hot temperatures
for temperature in daily_temperatures:
if temperature > 30:
hot_days = hot_days + [temperature] # or hot_days.append(temperature)
print('The hot days had temperatures', hot_days)

O/P: The hot days had temperatures [33, 32, 42, 36] 8

Transform
• Another way to construct a new list from an existing
one is to transform each item of the input list into
one item of the output list.

Problem 2.2 Celsius to Fahrenheit


• Convert a list of temperatures in degrees Celsius to a
list of temperatures in degrees Fahrenheit. Both
input and output temperatures can be floating-point
numbers.
• The pattern for the list transformation problem is as
follows.
9
Python editor: Celsius to Fahrenheit
# Problem: convert Celsius temperatures to Fahrenheit
# Input: a possibly empty list of temperatures in Celsius
celsius_values = [28, 33, 29, 32, 27,42,29,36]
# Output: the list of temperatures in Fahrenheit
fahrenheit_values = [] # a new list that will contain the transformed values
for celsius in celsius_values:
fahrenheit = celsius * 1.8 + 32
fahrenheit_values = fahrenheit_values + [fahrenheit] # or use append
print('The temperatures in Fahrenheit are',fahrenheit_values)

The temperatures in Fahrenheit are [82.4, 91.4, 84.2, 89.6,


80.6, 107.60000000000001, 84.2, 96.8]
10
Reduce
• A typical class of problems on lists is to reduce them to a single value, which
might or might not be in the list. For example, a list of strings might be
reduced to a single string that is the concatenation of all the strings in the list.
• In this and the next section you will see three types of reduction problems,
illustrated with numeric lists.
 Counting problems involve computing how many numbers are in the list, or
how many numbers in the list satisfy a certain condition, e.g. are non-zero.
 Aggregation problems are a generalization of counting problems. They
involve computing some new number (e.g. the sum or the product) out of all
or part of the numbers in the list.
 Retrieval (or search) problems involve finding a particular number in the list
that satisfies some condition, e.g. the largest number. Contrary to the other
two, in this type of problem the resulting number is always in the list.
• All these problems can be solved by similar programming patterns that use a
for- or while-loop and at least three variables: one for the list containing the
items to be processed, one to step through the items, and one to
incrementally compute the value the list is being reduced to. Learning to
recognize a problem – or part of a problem – as a reduction problem will
allow you to apply those patterns, even to non-numeric lists, instead of
thinking of a solution from scratch.

11
Count
• In its more general form, the counting problem asks for how
many items in a list satisfy some condition. Here’s an
example.

Problem 2.3 Negative Temperatures


• Given a list of daily maximum temperatures over a week-
long period, calculate how many days the temperature was
below zero.

12
Program 2.5 Negative temperatures
• Pattern 2.5 Counting:
1. initialize the input list.
2. set a counter to zero.
3. for each item in list:
Algorithm a. if the item satisfies the condition:
i. increment the counter, i.e.
add 1 to it.
4. print the counter.

# Problem: count how many days temperature was below zero


# Input: temperatures, a list of 7 numbers
temperatures = [4, -5, 3, 1, 0, 3, -2]
# Output: number of days, a non-negative integer
Python Code days = 0
for temperature in temperatures:
if temperature < 0:
days = days + 1 # or day+=1
print('The temperature was below 0 for', days, 'days')

The temperature was below 0 for 2 days 13


Count – List Length
• As a further example, let’s look at the quintessential counting problem
on lists.

Problem 2.4 List length


• Compute the length of a list, i.e. count how many items are in the
list.

• It is such a commonly recurring problem that Python has already


solved it:

• len (some_list) computes the length of some_list. Nevertheless, it is


instructive to see that there is no magic to it.

• The main difference to the general problem is that there is no


condition to check: all items count towards the length of the list.
14
Aggregate
• The aim of aggregation is to compute a new number from the
numbers in the list. The resulting number is computed incrementally
as we iterate through the list, by ‘aggregating’ each number in the list
into the result so far.

• A quintessential aggregation problem is the sum of a list of numbers:


each number in the list is added to the result so far.
• Again, this is such a recurrent problem that Python already provides
an expression for it:

 sum(some_list) – to sum all the element of some_list


 The pattern generalizes Pattern 2.5 for counting problems:

15
Program 2.7 list sum
• Pattern 2.6 Aggregate:

1. initialize the input list.


2. initialize the aggregator with a suitable value.
3. for each number in the list:
a. if the number satisfies the condition:
i. update the aggregator according
to the value of the number.
4. print the aggregator.

# Problem: compute the sum of a list of numbers


# Input: numbers, a possibly empty list of numbers
numbers = [4, -1, 3, 5, -4]
# Output: total
total = 0
for number in numbers: # you can replace this part with:
total= sum(numbers)
total = total + number
print('The sum of', numbers, 'is', total)

The sum of [4, -1, 3, 5, -4] is 7 16


Search

• A filtering problem (subsection 2.1.3) can also be seen as a


search problem: retrieve all the items that satisfy a particular
condition. In this section, we look at the problem of retrieving
any one item that satisfies the condition. Such a search
problem is a reduction problem and therefore will be solved in
a manner similar to other reduction problems.

• Search problems can be stated for all types of items, but


again the examples will be with numeric items.

17
Find a Value
• The pattern is similar to the previous reduction patterns: a
variable stores the item found so far, if any, which will be the final
result when the iteration over the list ends.
• The issue is, again, how to initialize the result variable.
• The trick is, again, to think what should happen if the list is empty.
In that case, the loop is not executed, so the final value of the
result variable will be the value it was initialized with.
• If the list is empty, there is no item to be found, and the output
should somehow represent ‘no item’.
• Some programming languages have a ‘null value’ for that. Hence
the result variable has to be initialized with the ‘null value’.

18
Program 2.8 Find Negative Temperature
• Pattern 2.7 Find value:

1. initialize the input list.


2. set found to the null value.
3. for each item in the list:
a. if the item satisfies the condition:
i. set found to the item.
4. print found.

# Problem: find a negative temperature during the week


# Input: temperatures, a list of 7 numbers
temperatures = [4, 5, 3, 1, 0, 3, -2]
# Output: a negative temperature, if it exists, or None
negative = None
for temperature in temperatures:
if temperature < 0:
negative = temperature
print(temperatures,'has negative temperature',negative)

[4, 5, 3, 1, 0, 3, -2] has negative temperature -2 19


Find the best value
• Another variation of the retrieval problem is to find the ‘best’ item
among a list, for some criterion of what ‘best’ means. Here is an
example.

Problem 2.5 Find The Coldest Day


• Given a list of daily temperatures, print the lowest value in the list.

• For this problem type, I will assume that the input list is not empty.
This guarantees that there will be a best value.

• The pattern to solve the general problem again uses a variable to


store the result so far, as we iterate over the list, but what is its initial
value? Since we have to go through the whole list to find the best
item, we can take any of the items as the baseline to compare
against. The simplest is to take the first item.
20
Program 2.9 Find Coldest Day
• Pattern 2.8 Find best value:
1. initialize the input with a non-empty list
2. set best to the first item in the list.
3. for each item in the list:
a. if the item is better than best:
I. set best to the item.
4. print best.

# Problem: find the lowest temperature of the week


# Input: a list of 7 numbers
temperatures = [5, 0, -3, 7, 8, 5, 0]
# Output: coldest, the lowest value in temperatures
coldest = temperatures[0]
for temperature in temperatures:
if temperature < coldest:
coldest = temperature
print('The lowest of', temperatures, 'is', coldest)
The lowest of [5, 0, -3, 7, 8, 5, 0] is -3
• Note: To avoid the redundant comparison, the loop should start with
the second item of the list, but that is not possible in an iterate-by-
21
item loop. If we iterate by position, then we can avoid it.
Program 2.9 Find Coldest Day
If we iterate by position, then we can avoid a redundant comparison
of the first item. The code will be:

# Problem: find the lowest temperature of the week


# Input: a list of 7 numbers
temperatures = [5, 0, -3, 7, 8, 5, 0]
coldest = temperatures[0]
# Output: coldest, the lowest value in temperatures
for i in range(1,len(temperatures)):
if temperatures[i] < coldest:
coldest = temperatures[i]
print('The lowest of', temperatures, 'is', coldest)

The lowest of [5, 0, -3, 7, 8, 5, 0] is -3

22
Block 2 (Part 4)
Organizing Your Python Code and Data

23
Functions in Python

• You may recall being told that you can find the size of a list named
gloves by using len(gloves). This involved a Python function,
len().

• The len() function is a built-in Python function: the Python


interpreter will know how to handle it, without you needing to add
any additional code to your program.

24
Function names and arguments
• When we talk about a function, we use its name – in this case, len – followed
by a pair of parentheses: len(). This way, you can see at once that we are
talking about a function rather than, for instance, a variable.

• In addition to a name, a function can have arguments (though not all


functions have arguments). In the example len(gloves), the variable
gloves is the argument of the function.

• When a function name is combined with its argument, the result is an


expression. As illustrated in Figure 4.2, combining the function name len
with the argument gloves results in the expression len(gloves).

Figure 4.2 The expression len(gloves) is


composed of the function name len and the
argument
25
Functions
Four parts of function’s definition:
1. The reserved word def which indicates that what
follows is a function definition.
2. The name of the function.
3. List of arguments enclosed in parentheses.
4. The body of the function, which is the set of
statements that carry out the work of the function,
noting that:
• Use colon ( : ) to start the body of the function.
• Use indentation for the body of the function .

def printHello():
print("Hello! ")

26
Functions without return
• Some functions perform simple procedural tasks (specified in their bodies)
but do not return any information when they are called.

• Example: Write a function that will display a welcome message to a student with
his/her name. Then, use the function in your program.
def welcome(aName):
print("Hello " , aName)
print("Welcome to AOU")
welcome("Ahmad") #Function call

• When the function is called, an actual value for the argument must be used.
• For example, when the function call welcome('Ahmad') is executed, the actual
string 'Ahmad' replaces the argument aName resulting in the following output:

-----output-----
Hello Ahmad
Welcome to AOU

27
Functions with return

• Some functions provide a value as the result of some calculations made in


the function’s body.
• Python provides us with the return statement:
return followed by the value it needs to return
• In order not to lose the returned value , you need to:
• assign it to a variable (for further calculations, if needed)
OR
• print it immediately.

28
Functions with return
• Example : Write a function that takes the height and width as arguments,
calculates the area of a rectangle, and returns it. Then display the area in the
output window. Use the function in your program.
4 6

def recArea(aHeight,
4
aWidth) :
6
area = aHeight * aWidth
return area

h = eval(input("Enter the height: " ))


w = eval(input("Enter the width: "))
print("Area = ",recArea(h,w)) #Function call inside
print()

-----output-----
Enter the height: 4
Enter the width: 6
Area = 24
29
Functions with Multiple return values
So what if you want to return two variables from a function instead of one?
There are a couple of approaches which new programmers take.
Let’s take a look at a simple example:

# example on multiple return vales # example on multiple return vales


def profile(): def profile():
name = input('Enter your name: ') name = input('Enter your name: ')
BD = int(input('Enter your birth date: ')) BD = int(input('Enter your birth date: '))
age= 2020- BD The returned values are age= 2020- BD
return [name, age] now in a list return name, age
Capturing the returned The returned
profile_data = profile() values in the list name, age = profile() values are
profile_data assigned to
print('Name: ',profile_data[0]) print('Name: ',name) variables
print('Age: ',profile_data[1]) Retrieving each print('Age: ',age)
item by its index
Enter your name: Naji Enter your name: Naji
Enter your birth date: 1999 Enter your birth date: 1999
Name: Naji Name: Naji
Age: 21 Age: 21

30
Hiding Complexity: Interfaces and
Implementations
• When a function is called, the resulting value is referred to as the return
value of the function.

• To use a function, all you need to know are:

• the name of the function.


• what kind of argument(s) it needs.
• what it gives back as a return value.
• what other effects calling the function has.

• There is a name for the items you need to know: the interface of the
function. To use a function, knowing the interface is enough. There’s no
need to know what goes on under the bonnet-its implementation.

• When the implementation is separated from the interface, thereby hiding


some of the complexity, we also say that an abstraction has been created.
31
The Python Interpreter and Functions

• The Python interpreter deals with a program one line after the
other, starting with the very first line. A normal program line is
executed when the interpreter gets to it. However, functions do
receive special treatment, which we examine in this section.

• When the Python interpreter encounters a function definition, it


reads this definition into memory for later use.

• The interpreter only executes the lines of a function definition,


when the function is called.

32
The Python Interpreter and Functions

• On those occasions where a function is called, the parameters are


initialized with the actual arguments and then the statements in its
body are executed.
• On encountering the keyword return, Python does two things:

1. the function stops executing (control is handed back to the


point where the function was called originally)
2. the value of the expression following return is passed back. In
other words, the evaluation of the function expression is
complete and the result is the return value of the function.

33
Using Functions- The Benefits
• Replacing duplicate code with a function can make a program
shorter and more readable.

• A further advantage is that it makes it much easier to modify the


code, if needed.

• In short, functions can help us write code that:

 is shorter and consequently more readable.


 is easier to change, making it less likely that errors are
introduced.
 explicitly mirrors the decomposition of a problem and
consequently is easier to understand.

34
Reusing Code
• There is a more elegant way to reuse functions. Instead of
copying a function into a new program, you can also put all
your functions – say, for drawing figures – into a separate file
(with the .py extension). Let’s call it
figure_drawing_functions.py. At the beginning of
your new program, you then simply add from
figure_drawing_functions import *. This has the
same effect as placing the function definitions themselves at
the beginning of the program. This way, you can create your
own library of figure drawing functions.

• Important note: You will need to make sure that


figure_drawing_functions.py is in the same folder as
your new program, otherwise Python won’t be able to find it.

35
Summary
• In this part, you again practiced the techniques to solve
computational problems by:
1. looking in the problem statement for the input(s) and the
output(s)
2. thinking which inputs are not allowed, e.g. negative
numbers or empty lists
3. writing tests (pairs of admissible inputs and their
expected outputs)
4. recognizing the type of the problem or the types of the
sub-problems
5. instantiating the patterns for those problem types
6. combining the algorithms for the sub-problems to solve
the whole problem.
7. organizing your code using functions.

• You have seen more examples of different thinking


approaches. 36

You might also like