0% found this document useful (0 votes)
22 views54 pages

Slides 10

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views54 pages

Slides 10

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 54

Functions Part 2

Section 2
Chapter 4

1
Quiz 10 code:

Time Limit: 10 minutes

For questions about the quiz on Piazza, please postpone your post until Friday afternoon
or after.

2
Agenda
• Functions calling other functions

• Function default values, passing by parameter name, lambda

• List comprehension

• Dictionary

• Recursion

• Programming design

3
Functions Calling Other Functions
• Function can call another function

• When the called function terminates


• Control returns to the place in calling function just after where
function call occurred.

4
Example 1: functions calling other functions
Functions Returning Multiple Values
• Functions can return any type of object, not just a
number, string, or Boolean value.

• For instance, a function can return a tuple or a list


of numbers.

6
Example 2A

7
Example 2B

8
Recall: User-defined Functions
• Three ways to pass arguments to parameters:
• Pass by position, pass by keyword, and pass by default value.

• In last section, we consider pass by position - arguments in calling statement


matched to the parameters in function header based on order.

• the 1st argument is passed to the 1st parameter, the 2nd argument is passed
to the 2nd parameter, and so on.

• Parameters and return statements are optional in function definitions

• Function names should describe the role performed

9
Default Values
• Parameters of a function can have default values
• Assigned to them when no values are passed to them

• Format for definition using default values

10
Default Values
Default Values
Passing by Parameter Name
• Arguments can be passed to functions by using names of
the corresponding parameters
• Instead of relying on position

13
Lambda Expression
• One-line mini-functions
• Can be used where a simple function is required.
• Compute a single expression
• Cannot be used as a replacement for complex functions

• Format
• Where expression is the value to be returned

14
Lambda Expression

15
Recall: range() function

16
List Comprehension
• Simpler way to apply a certain function to each item of a
list
• Use list comprehension

• The for clause in a list comprehension can optionally be


followed by an if clause.

17
Example 7: List Comprehension
Example 8: List Comprehension with if

19
Recall Classwork 9: Present Value of Ordinary
Annuity
• Define a function that calculates the present value of an ordinary annuity – there is a fixed
amount of cash flow at the end of each period. Assume the beginning balance is zero.
• The function's arguments will include
• the fixed amount of cash flow;
• the discount rate;
• the number of periods.
• Use a repetition structure (for loop or while loop) when defining the function.
• The function will be capable of the following. Follow the same submission requirement (.py
file and screenshot) as before.

20
Present Value of Ordinary Annuity
• Example. The following calculates the present value of an annuity over five years
with $1000 at the end of each year and a 5% annual discount rate.

21
Classwork 9: list comprehension solution

22
Recall: List operations

23
Dictionaries
• Python dictionary is defined as
• A collection of comma separated pairs
• Of the form key:value
• Enclosed in curly braces.

• Value associated with key1 is given by the expression


dictionaryName[key1].

• Dictionary keys must be immutable objects.


• Lists and sets cannot serve as keys!

24
Dictionaries

25
Dictionaries
list(d.values) returns a list of the values in the dictionary
list(d.items) returns a list of two-items tuple of the form (key, value) where d(key) = value
list(d) returns a list of the keys in the dictionary

26
The dict Function
• List of 2-item lists or 2-item tuples can be converted to a
dictionary with dict function

27
Dictionary shortens scripts

Program with long if-elif statement can be simplified with use of a dictionary.

28
Dictionary Comprehension
• Dictionaries can be created with dictionary
comprehension.

29
Recursion
Section 4
Chapter 6

30
A Recursive Power Function
• Recursive function invokes/calls itself
• Successive calls reduce to simpler task
• Until base case with trivial solution reached
• The nth power of a number
• Iteratively

• Recursively

31
Iterative definition of power function

32
A Recursive Power Function
• Definition uses the recursive definition of a power.

33
A Recursive Power Function
A Recursive Power Function
Traits of recursive algorithms
1. One or more base cases with direct solutions.
2. An "inductive step"
– Reducing the problem to one or more smaller versions of the same
problem
– Reduction eventually culminating in a base case.
– Called the reducing step.

35
Recursive Palindrome Function
• Sometimes a recursive solution is easier to understand and to
code than iterative routine.
• Function uses recursion to determine whether or not word is a
palindrome. A word is a palindrome if it reads the same forward
and backward, e.g., racecar, kayak, and pullup

36
Recursive Function: Reversed List
• Write a recursive function to reverse a list.

37
Recursive Function: Reversed List
• Write a recursive function to reverse a list.

38
Recursive Function: Sum of digits
• Write a recursive function to compute the sum of digits of a
positive integer.

39
Recursive Function: Sum of digits
• Write a recursive function to compute the sum of digits of a
positive integer.

40
Program Design
Section 3
Chapter 4

41
Top-Down Design
• To make a complicated problem more
understandable
• Divide it into smaller, less complex subproblems.
• Called stepwise refinement

• Top-down design and structured


programming
• Techniques to enhance programming
productivity

42
Top-Down Design
Criteria
1. Design should be easily readable and emphasize small
module size.
2. Tasks proceed from general to specific as you read
down the chart.
3. Subtasks should be single-minded.
4. Subtasks should be independent of each other.

43
Top-Down Design
Top-Down Design
Criteria
1. Design should be easily
readable and emphasize
small module size.
2. Tasks proceed from general
to specific as you read
down the chart.
3. Subtasks should be single-
minded.
4. Subtasks should be
independent of each
other.
Structured Programming
• A program is structured if it meets modern standards of program
design

• Use top-down design

• Use only the three types of logical structures:


• Sequences – Statements executed one after the other
• Decisions – blocks of code executed based on test of some condition
• Loops – blocks of coded executed repeatedly based on some condition

46
Advantages of Structured Programming
• Easy to write

• Easy to debug

• Easy to understand

• Easy to change

47
Kahoot
• Go to https://kahoot.it/

• Enter the game PIN as shown on the classroom projector.

• Enter your 8-digit student ID, E.g., 55123456


Do NOT use names.

• Kahoot is separate from the weekly quiz on Canvas. Kahoot


engagement (not merit) will partially determine class participation
scores.

48
Classwork 10: Recursion
Create a Python function fib(n) that returns the 𝑛th term of the Fibonacci
sequence.
1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ⋯
The first two terms of the sequence are both 1. Starting from the third term,
the 𝑛th term is the sum of the two preceding terms. For example, the 3rd
term is the 2nd term plus the 1st term: 1 + 1 = 2. The 4th term is the 3rd term
plus the 2nd term: 2+1 = 3.
Use recursion to define the function.

49
50
Homework 9
Define a function caesar(message, shift) that encrypts messages based on Caesar cipher (see
Classwork 3). The function's arguments will include

1) a message;
2) the number of shifts in the cipher.

The output of the function is an encrypted message. Spaces and punctuation are not encrypted and
are included in the output. The function should be capable of the following.

Hint: Since the length of the message is not fixed (and can be very long), it is
best to use a repetition structure (e.g., a for loop over the original string). One
can start with an empty string as in Example 4, Slides 6. Under the for loop, if
a character is a letter, encrypt it following the Classwork 3 solution. Otherwise,
no encryption is needed for that character.

51
Homework 9
# Define caesar(message, shift):
# Set the output to be an empty string in the beginning
# for each character in the message:
# If the character is a letter, get the shifted letter (see CW3) and
add it to the output string.
# Else, just add the character to the output string.
# Return the output string.

Mind the different levels of INDENTS!

52
Recall: List indexing
• The .find() method only works with strings.

• Lists have a similar method: .index()

© 2016 Pearson Education, Ltd. All rights reserved. 53


Recall: find and rfind

If subStr is a string, then str1.find(subStr) is the positive


index of the first appearance of subStr in str1 with the
search beginning at the left side of the string.

The value of str1.rfind(subStr) is the positive index of


the first appearance of subStr in str1 with the search
beginning at the right side of the string.

© 2016 Pearson Education, Ltd. All rights reserved. 54

You might also like