4 ms·
Sure, what I meant by the "obvious" way of making some polynomials is: polys = [] for i in range(0,4): polys.append(lambda x: x**i) But that a
by sixbrx 8y ago
Sure, what I meant by the "obvious" way of making some polynomials is:
polys = []
for i in range(0,4):
polys.append(lambda x: x**i)
But that actually just yields the same polynomial x -> x^3 in each element of polys array:
polys[0](2)
> 8
polys[1](2)
> 8
polys[2](2)
> 8
The same thing happens if we use a list comprehension:
polys = [lambda x: x**i for i in range(0,4)]
The trick is to add a default argument value to the lambda, which catches "i" by value instead of by reference:
for i in range(0,4):
polys.append(lambda x, i=i: x**i)
And now we get the different polynomials we expected:
polys[0](2)
> 1
polys[1](2)
> 2
polys[2](2)
> 4
polys[3](2)
> 8