How To Create A Set Of Parametrized Functions In Python?
I am trying to create a family of functions, parametrized by a 'shift' parameter. Consider the code below. I want the for loop to create a set of functions, each of which shifts th
Solution 1:
The difference in output in both the loops in because of the difference in the value of idx
.
In your first for
loop, you stored the reference of function f()
in fns
list. Here, value of idx
is not stored as part of your function f()
inside fnx
.
for idx inrange(N):
deff(x): # shift input by idxreturn x+idx
fns.append(f)
Once you executed this loop, idx
is holding the value as 4
(N-1 from the for
loop).
Hence, your second loop print the values using idx
as 4
. i.e. f()
printed the value 4+1
for i in range(N):
print(fns[i](1))
However in your 3rd loop, you are re-initializing the the value of idx
as part of for
loop and your fns
is getting the value in range 0 to 4 with each iteration.
for idx in range(N):
print(fns[idx](1))
That's why you see the value ranging from 1 to N here (because of idx
ranging from 0 to N-1).
Post a Comment for "How To Create A Set Of Parametrized Functions In Python?"