Control
Print and None
- Pure functions just returns a value. None-pure functions have a side effect.
- Print is a none-pure function that always returns None, but also displays a given value.
- Practice: Implement a function h(x) that first prints, then returns, the value of f(x)
1
2
3
4
5
6
7
8
9
10
11
def f(x):
return print(x+1)
def h(x):
print(f(x))
return f(x)
def h2(x):
y = f(x)
print(y)
return y
1
h(2)
1
2
3
3
None
3
1
h2(2)
1
2
3
None
1
2
3
4
5
6
7
8
9
10
def f(x):
return square(x + square(y+1))
def square(z):
y = z * z
return y
x, y, z = 1,2,3
print(f(3))
1
25
Multiple Environments
- Start from the earliest local frame, and trace back up in the environment until we reach the global frame.
- A function that is defined within another function can access local parameters of the parent function.
Control
Conditional Statements.
- COnditional statements contain statements that may or may not be evaluated.
Iteration
While Statements:
- Contains stateemnts that are repeated as long as the condition is true.
- Must eventually become a false for the statement to end (or return/break or some statement to stop iteration)
- Entire body is executed.
Prime Factorization
- Every positive integer n has a set of prime factors: primes whose product is n
1
2
3
4
5
6
7
...
8 = 2 * 2 * 2
9 = 3 * 3
10 = 2 * 5
11 = 11
12 = 2 * 2 * 3
...
- My code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
def prime_factorize(n):
k = n
factors = []
curr = 2
while (k%curr==0):
factors.append(curr)
k//=curr
curr = 3
while (curr<=n):
while (k%curr==0):
factors.append(curr)
k//=curr
curr = curr+2
return factors
prime_factorize(1298237392)
1
[2, 2, 2, 2, 23, 3527819]
Jedi’s Example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
def prime_factors(n):
"""
Print out all the prime factors of n
>>> prime_factors(6)
2
3
"""
# Continue to do this until n == 1
while n != 1:
k = smallest_factor(n) # find smallest factor of n
print(k)
n = n // k
def smallest_factor(n):
"""Return the smallest factor of n greater than 1."""
k = 2
while n % k != 0:
k += 1
return k
prime_factors(6)
1
2
2
3