0% found this document useful (0 votes)
6 views

Week8_Functions_Ctd_2

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Week8_Functions_Ctd_2

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

Ceng 240

Week 8
Functions
(Continued)
This Week’s Content
• Higher-Order Functions
• Recursion
• Examples of Functions
Higher Order Functions: map
• Python provides two very special higher-order
functions:
• map function:
• Syntax: map(function, Iterator)
• Yields an iterator where each element is a function
being applied on the corresponding element in the
Iterator.
• Here is a simple example:
Higher Order Functions: filter
• filter function:
• Syntax: filter(predicate, Iterator)
• where predicate is a function with a boolean return
value
• The filter function applies predicate to each element of
the Iterator and only keeps ones for which predicate
returns True
• Here is a simple example:
Higher Order Functions
• The functional capabilities of Python is more
diverse than we can cover in this introductory
lecture
• You can refer to Python Docs for more details.
• Especially recommended:
• lambda expressions
• the reduce function.
Recursion
Recursion
• Recursion is a function definition technique in which the definition makes use of
calls to the function being defined.
• A recursive function is a function that calls itself

• Here is the recursive definition of factorial.


• First, let us put it down in mathematical terms:

• Based on this, we can realize that:

• Substituting any factorial value, based on this rule, one ends up with:
Recursion
• Making use of (𝑁−1)! while we are defining 𝑁! is making a recursive definition.

• The Python equivalent of the above given recursive mathematical definition of the
factorial would be:

• High-level languages are designed so that each call to the factorial function
does not remember any previous call(s) even if they are still active
(unfinished).

• For every new call, fresh positions for all local variables are created in the
memory without forgetting the former values of variables for the unfinished
calls.
Recursion
• To prevent an infinite, non-stopping recursive loop, you should be
careful about two aspects:
1. The recursive call should be made with a smaller argument:
• In the factorial example, calculation of 𝑁! recursively
called (𝑁−1)!, i.e. a smaller value than 𝑁!.

2. The function definition must start with a test for the smallest
possible argument case where a value for this case is directly
returned:
• In the factorial example, this was 0 (zero)
• This is called the termination or base condition.
Examples of Functions
Example 1: Computing average
and standard-deviation
• In the previous chapter, we provided iterative definitions for calculating the
average and the standard-deviation of a list of numbers.
• Let us look at these definitions again with functions.
• For the sake of ease, the mathematical definitions are provided again.
• Moreover, we will use this opportunity to talk more about iterations as well.
• Average of a set (𝑆) of numbers is calculated by dividing the sum of the values in
the set by their number. So, if we have a set 𝑆:
Example 1: Computing average
and standard-deviation

• The formula can be coded as the following:


Example 1: Computing average
and standard-deviation
• Sometimes it is more desirable to work with the indices to reach out to each
element.
• Remember that indexing of container elements start at zero.
• A more index-based formulation of the same formula would be:

• The following implements this definition:


Example 1: Computing average
and standard-deviation

• This is almost okay but not perfect: len is a built-in function that returns the element count of
any container (string, list, tuple).
• As you have observed len(S) is calculated twice.
• This is inefficient.
• Function calls have a price, time-wise and space-wise, and therefore, unnecessary calls should
be avoided.
• To fix this, we change the code to do computation once and store the result for further usages
Example 1: Computing average
and standard-deviation
• Now let us also introduce the code for standard deviation.
• First the mathematical definition:
Example 1: Computing average
and standard-deviation
• We gave the solution in terms of explicit indexing.
• As given below this particular problem can be coded without an iteration over indices.
• Such problems are rare.
• Problems that require operations over vectors and matrices or problems that aim
optimizations usually require explicit index iterations.
• For sake of completeness we state the index-less solution of the average and standard-
deviation problem:
Example 2: Computing check-digit
• A Standard Definition from Wikipedia:
• “A check digit is a form of redundancy check used for error detection on
identification numbers, such as bank account numbers, which are used in
an application where they will at least sometimes be input manually.

• It consists of one or more digits computed by an algorithm from the other


digits (or letters) in the sequence input.

• With a check digit, one can detect simple errors in the input of a series of
characters (usually digits) such as a single mistyped digit or some
permutations of two successive digits.”

Example 2: Computing check-digit
• Middle East Technical University, our university, also implements a check digit
algorithm for student numbers.
• A student number has exactly six digits.
• The algorithm to generate the checkdigit is as follows:
• 𝑠𝑢𝑚←0
• For each digit in the student number (the leftmost digit is the named as the ‘first’)
that has an odd position (first, third, fifth), take the digit and add it to the 𝑠𝑢𝑚.
• For each digit in the student number that has an even position (second, forth, sixth)
take twice the digit. If this result of doubling is a two digit number, then add each
of these digits to the 𝑠𝑢𝑚, otherwise add the result of the doubling (which is a
single digit number itself) to the 𝑠𝑢𝑚.
• The one digit number, which when added to the 𝑠𝑢𝑚 results in a multiple of 10, is
the check digit.

Example 2: Computing check-digit
• Example check digit calculation:

• The check digit of the student number 167912 is found to be 5.


• As you all well know, this is written as 167912-5. That is called the student-id.
Example 2: Computing check-digit
• Below you will find the code that computes the checkdigit for a student
number, given as a string.
Example 3: Sequential Search
• Searching an item in a list or any other container is a frequently performed
operation required while solving world problems.
• For the sake of simplicity, let us just focus on situations where only numbers are
involved;
• i.e. the searched item is a number and the list includes only numbers.
• Extension to other data types is trivial.
• In a search problem,
• we have a query item (let’s call it x) and
• a list of items (let’s call it L).
• If x is a member of L, then we want the search algorithm to return True,
• Optionally by returning its index in L.
• If x is not a member of L, we expect the algorithm to return False.
• Consider the example list below:

• If x is 4, the search algorithm should return True.


• If x is 5, the answer should be False.
Example 3: Sequential Search
• Let us start with the simplest algorithm we can use: Sequential Search.
• In sequential search, we start with the beginning of the list, go over each item in
the list and check if the query is equal to any item that we go over.
• Here is the algorithm:

• Let us implement this simple algorithm in Python


Example 3: Sequential Search
• Let us implement this simple algorithm in Python:
Example 3: Sequential Search
• We can have a more compact solution using for loops:
Example 3: Sequential Search
• Let us have a look at a recursive solution.
• First, let us have a look at the algorithm.
• The idea is essentially the same:
• We compare with the first item and return True if they match.
• Otherwise, we continue our search with the remaining items.
Example 3: Sequential Search
• Here is the implementation in Python:
Example 4: Binary Search
• If the list of items (numbers in our case) is not sorted, sequential search is the only
option for searching for an item.
• However, if the numbers are sorted, then we have a much more efficient algorithm
called binary search.
• Assuming that L, our list of numbers, is sorted in an increasing order:
• In binary search, we make our first comparison with the number that is at the
center (middle) of the list.
• If the middle number is equal to x, then we obviously return True.
• Otherwise, we compare x with the middle number:
• If x is smaller, then it has to be to the left of the middle number – we can continue
our search on the left part of L.
• If, on the other hand, x is larger than the middle number, it has to be on the right
side of the middle number – we can continue our search on the right part of L.
• This is illustrated in the following figure.
Example 4: Binary Search
• Here is the pseudocode that describes this algorithm:

• The following is the implementation in Python:


Example 4: Binary Search

You might also like