Designing Functions
- A function’s domain is the set of all inputs it might possibly take as arguments.
- A function’s range is the set of output values it might possibly return
- A pure function’s behavior is the relationship it establishes between the input and output.
- Good programmer practice: Implement a process only once and do not repeat it many times.
1
2
3
4
5
6
7
8
9
10
# same_length.py
def digits(a, b):
a_digits = 0
while a > 0:
a = a // 10
a_digits = a_digits + 1
return a_digits
def same_length(a,b):
return digits(a) == digits(b)
Higher Order Functions
- Functions can be passed as parameters to another function.
- Summation Example
1
2
3
4
5
6
7
8
9
10
def cube(k):
return pow(k, 3)
def summation(n, term):
total, k = 0, 1
while k <= n:
total, k = total + term(k), k+1
return total
summation(5, cube)
1
225
Program Design
- Modularity: Simple objects can be combined to create more complex operations
- Abstraction: We can hide complex operations behind a name and trust that it works every time.
- Separation of Concerns (??)
Functions are Return values
- Locally Defined Functions
- Functions that are defined within other function bodies are bound to names in a local frame
Twenty-One Game
- Example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
def play(strategy0, strategy1, goal=21):
n = 0
who = 0
while n < goal:
if who == 0:
n = n + strategy0()
who = 1
elif who == 1:
n = n + strategy1()
who = 0
return who
def three_strategy():
return 3
play(three_strategy, three_strategy)
1
1