CS1010S Tutorial 8 PDF
CS1010S Tutorial 8 PDF
CS1010S Tutorial 8 PDF
d[1] = 2
print(d[1]) -> 2
Quick Recap
- def f(*args):
widget = make_widget()
widget("insert", 1)
widget("insert", 2)
widget("insert", 3)
2
Q2
>>> A = make_accumulator ()
>>> A ( 10 )
10
>>> A ( 10 )
20
Q2
def make_accumulator():
def helper(n):
return helper
Q2
def make_accumulator():
result = [0]
def helper(n):
result[0] = result[0] + n
return result[0]
return helper
Q3
>>> s = make_monitored ( sqrt )
>>> s ( 100 )
10 . 0
>>> s ("how -many - calls ?")
1
>>> s ( 1024 )
32 . 0
>>> s ("how -many - calls ?")
2
>>> s ("reset - count ")
>>> s ("how -many - calls ?")
0
Q3
def make_monitored(f):
state = 0
def mf(msg):
if msg == "how-many-calls?":
return state
elif msg == "reset-count":
state = 0
else:
state = state + 1
return f(msg)
return mf
Q3
def make_monitored(f):
state = 0
def mf(msg):
nonlocal state
if msg == "how-many-calls?":
return state
elif msg == "reset-count":
state = 0
else:
state = state + 1
return f(msg)
return mf
Q3
make_monitored for such
functions with more args?
def sum_numbers (* numbers ):
s=0
for n in numbers :
s += n
return s
>>> sum_numbers (1 ,2 , 3 )
6
>>> sum_numbers (1 ,2 ,3 ,4 , 5 )
15
Q3
else:
state[0] = state[0] + 1
return f(*args)
Q4
Monte-carlo Integration
(a) "run trials" and a number of trials to run and performs the stated
number of trial.
(b) "trials" will return the number of trials run thus far.
(c) "get estimate" to return the current estimate given the trials run so far.
Q4
def make_monte_carlo_integral(P,x1,y1,x2,y2):
count = [0,0]
area = abs(x2-x1)*abs(y2-y1)
def oplookup(msg,*args):
if msg == "run trials":
for i in range(args[0]):
if P(random.uniform(x1, x2),random.uniform(y1, y2)):
count[0] += 1
count[1] += 1
elif msg == "trials":
return count[1]
elif msg == "get estimate":
return area * count[0]/count[1]
return oplookup
Q5
For example:
>>> translate (" dikn "," lvei ","My tutor IS kind ") "My tutor IS evil "
Q4