python - Sympy and lambda functions -
this question has answer here:
i want generate list of basic monomial x^0 x^n (in particular, n=9) using sympy. quick solution simple list comprehension combined python's lambda function syntax:
import sympy sym x = sym.symbols('x') monomials = [lambda x: x**n n in range(10)]
however, when verify monomials
constructed expected, find that:
print([f(x) f in monomials]) >>> [x**9, x**9, x**9, x**9, x**9, x**9, x**9, x**9, x**9, x**9]
if redefine monomials
without using lambda syntax, otherwise expect:
monomials = [x**n n in range(10)] print(monomials) >>> [1, x, x**2, x**3, x**4, x**5, x**6, x**7, x**8, x**9]
why behavior?
specs:
- python 3.5.1
- sympy 1.0
i using anaconda 2.5.0 (64-bit) package manager.
you need use second arg default value
monomials = [lambda x, n=n: x**n n in range(10)]
otherwise have closure , not value reference n
.
Comments
Post a Comment