1
2
3
ṅ
0 1 1 2 3 5 8 13 21 34 …
4
ṅ
0+1=1 2 3 5 8 13 21 34…
4
ṅ
0 1+1=2 3 5 8 13 21 34…
4
ṅ
0 1 1+2=3 5 8 13 21 34…
4
ṅ
0 1 1 2+3=5 8 13 21 34…
4
ṅ
0 1 1 2 3 +5 =8 13 21 34 …
4
ṅ
0 1 1 2 3 5 +8 =13 21 34 …
4
ṅ
0 1 1 2 3 5 8+13=21 34…
4
ṅ
0 1 1 2 3 5 8 13+21=34…
4
5
n: 1 2 3 4 5 6 Σ:1 1 2 3 5 8
6
VF0 1 1 2 3 5 8 13 21 34 55… N 0 1 2 3 4 5 6 7 8 9 10…
def vf_number(n):
“””Compute the nth Virahanka-Fibonacci number, for N >= 1. >>> vf_number(2)
1
>>> vf_number(6)
8
“””
prev = 0 # First Fibonacci number
curr = 1 # Second Fibonacci number
k=1
while k < n:
(prev, curr) = (curr, prev + curr)
k += 1 return curr
7
13×13
21×21
8×8
5×5
8
9
10
def square(x):
"""Returns the square of X.""" return x * x
x square
square
x
11
round(1.23) # 1
round(1.23, 0) # 1
round(1.23, 1) # 1.2
round(1.23, 5) # 1.23
12
13
14
from math import pi, sqrt def area_square(r):
return r * r def area_circle(r):
return r * r * pi
def area_hexagon(r):
return r * r * (3 * sqrt(3) / 2)
15
from math import pi, sqrt
def area(r, shape_constant):
"""Return the area of a shape from length measurement R.""" if r < 0:
return 0
return r * r * shape_constant
def area_square(r): return area(r, 1)
def area_circle(r): return area(r, pi)
def area_hexagon(r):
return area(r, 3 * sqrt(3) / 2)
16
17
18
19
def cube(k): return k ** 3
def summation(n, term):
"""Sum the first N terms of a sequence. >>> summation(5, cube)
225
“””
total = 0
k=1
while k <= n:
total = total + term(k)
k=k+1 return total
20
21
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
22
make_adder(1)( 2 )
23
make_adder(1)( 2 )
make_adder(1)
23
make_adder(1)( 2 )
make_adder(1)
func make_adder…
23
make_adder(1)( 2 )
make_adder(1)
1
func make_adder…
23
make_adder(1)( 2 )
make_adder(1)
1
func make_adder…
make_adder(n)
def adder(k):
return k + n
return adder
fu
23
nc
make_adder(1)( 2 )
make_adder(1)
1
func make_adder…
make_adder(n)
def adder(k):
return k + n
return adder
fu
23
nc
make_adder(1)( 2 )
2
make_adder(1)
1
make_adder(n)
def adder(k):
return k + n
return adder
func make_adder…
fu
23
nc
make_adder(1)( 2 )
2
make_adder(1)
1
make_adder(n)
def adder(k):
return k + n
return adder
func make_adder…
fu
23
nc
24
lambda
expression
25
lambda
expression
square = lambda x: x * x x*x
square
x
25
square = lambda x: return x * x
square = lambda x: x * x
26
def square(x): square = lambda x: x * x return x * x
def
27
def cube(k): return k ** 3
summation(5, cube)
summation(5, lambda k: k ** 3)
28
29
30
lambda x: if x > 0: x else: 0 lambda x: x if x > 0 else 0
31