Write a function make_monitored that takes as input a function, f, that itself takes one input. The result returned by make_monitored is a third function, say mf, that keeps track of the number of times it has been called by maintaining an internal counter.
If the input to mf is the special string "how-many-calls?", then mf returns the value of the counter.
If the input is the special string "reset-count", then mf resets the counter to zero. For any other input, mf returns the result of calling f on that input and increments the counter.
def make_monitored(f):
a=[0]
def mf(x):
if x=="how-many-calls?":
return a[0]
elif x=="reset-count":
a=[0]
else:
a[0]+=1
return f(x)
return mf
def double(x): #NOT TO BE CHANGED , provided by question
return 2 * x
d = make_monitored(double) #NOT TO BE CHANGED, provided by question
here is what i dont understand: I want to make a one element list to make as an internal counter. I dont get why they say a is not defined when make_monitored is the parent function and i have defined a.
This is another question that i have completed previously (and correctly) that makes use of a similar method, but succeeds.
An accumulator is a function that is called repeatedly with a single numeric argument and accumulates its arguments into a sum. Each time it is called, it returns the currently accumulated sum. Write a function make_accumulator that generates accumulators, each maintaining an independent sum.
def make_accumulator():
lst=[0]
def add(x):
lst[0]+=x
return lst[0]
return add
A=make_accumulator()
Sample execution:
A = make_accumulator ()
A(10) output :10
A(10) Output :20
I dont get why lst[0] is accepted to be defined here. The only possible reason is that make_accumulator takes in no parameters but make_monitored does take in 1.
The assignment a = [0]
creates a new a
, which is local to mf
. And that means that all other references to a
in mf
must be to that local a
instead of the one in the parent.
So avoid assigning to a
itself and instead mutate it:
a[0] = 0
BTW, Python 3 provides a new keyword nonlocal
which is handy for this sort of thing. It works similarly to the global
keyword, and you could use it here to have a simple int for your counter or accumulator, rather than messing around with an int inside a mutable container.