05-Higher-Order Functions 4pp
05-Higher-Order Functions 4pp
Prime Factorization
Each positive integer n has a set of prime factors: primes whose product is n
...
8 = 2 * 2 * 2
9 = 3 * 3
10 = 2 * 5
11 = 11
Example: Prime Factorization 12 =
...
2 * 2 * 3
(Demo)
4
The Fibonacci Sequence
0,
1,
1,
2,
3,
fib pred 5,
8,
curr 13
,
n 5 21
,
34
5
4
3
2
1 ,
k 55
Example: Iteration ,
89
,
14
4,
23
3,
def fib(n): 37
7,
"""Compute the nth Fibonacci number, for N >= 1.""" 61
0,
pred, curr = 0, 1 # 0th and 1st Fibonacci numbers 98
7
k = 1 # curr is the kth Fibonacci number
while k < n:
pred, curr = curr, pred + curr
k = k + 1
return curr The next Fibonacci number is the sum of
the current one and its predecessor
Go Bears!
Boolean Contexts
def absolute_value(x):
"""Return the absolute value of x."""
if x < 0:
return -x
elif x == 0:
return 0
Control else:
return x
George Boole
10
(Demo)
14
The common structure among functions may be a computational process, rather than a number.
5
X
k =1+2+3+4+5 = 15
k=1
Higher-Order Functions
5
X
k 3 = 13 + 23 + 33 + 43 + 53 = 225
k=1
5
X 8 8 8 8 8 8
= + + + + = 3.04
(4k 3) · (4k 1) 3 35 99 195 323
k=1
(Demo)
16
hof.py Page 2
return total
Summation Example
def identity(k):
return k
Function of a single argument
def cube(k): (not called "term")
return pow(k, 3)
A formal parameter that will
def summation(n, term): be bound to a function
"""Sum the first n terms of a sequence.
def make_adder(n):
"""Return a function that takes one argument k and returns k + n.
>>> add_three = make_adder(3)
>>> add_three(4)
7
"""
def adder(k):
return k + n
return adder
@main
def run():
interact()