I am trying to make a program that creates a list of lambda functions of the format y=mx+b
, where 'm' and 'b' are predetermined values
My overall goal is to implement a function that
Basically, something like a Hough transforms if you know what that is.
Once I have the lines for a specific image, I can create a lambda function to represent the slope of the line and where it begins. I'm having an issue not being able to append a lambda function to the list.
I have tried this :
if __name__ == "__main__":
nums = []
for i in range(10):
j = lambda x: x + i
nums.append(j)
for i in nums:
print(i(1))
Here is the error I'm getting :
Traceback (most recent call last):
File "C:/Users/me/.PyCharmCE2018.3/config/scratches/scratch_3.py", line 7, in <module>
print(i(1))
File "C:/Users/me/.PyCharmCE2018.3/config/scratches/scratch_3.py", line 4, in <lambda>
j = (lambda x: x + i)
TypeError: unsupported operand type(s) for +: 'int' and 'function'
The problem is that the lambdas you create are referring to the current value of i
in the active stack frame. When you later reuse i
for the second for
loop, it is bound to the lambdas in your list. When invoked as i(1)
, the lambdas are trying to evaluate 1 + i
where i
is the lambda, so of course you get an error.
Probably what you want is to freeze the value of i
at the point at which the lambda is created. You can do this by replacing:
j = lambda x: x + i
with:
j = (lambda y: lambda x: x + y)(i)
This effectively captures the current value of i
by binding it to a lambda variable, then immediately applying that lambda, after which the binding remains fixed.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments