how do I find out how many arguments a lambda function needs
least-squares, numpy, python, scipy
Solution
under python >= 2.7:
>>> l = lambda a, b: None
>>> l.func_code.co_argcount
2
or under 2.6:
>>> l.__code__.co_argcount
2
Problem
I'm trying to create a function that will do a least squares fit based on a passed in lambda function. I want to create an array of zeroes of length equal to that of the number of arguments taken by the lambda function for the initial guess to the lambda function. so if its linear I want [0,0] and for quadratic I want [0,0,0]. ``` #polynomial functions linear = lambda p, x: p[0] * x + p[1] quadratic = lambda p, x: p[0] * x**2 + p[1] * x + p[2] cubic = lambda p, x: p[0] * x**3 + p[1] * x**2 + p[2] * x + p[3] #polynomial functions forced through 0 linear_zero = lambda p, x: p[0] * x quadratic_zero = lambda p, x: p[0] * x**2 + p[1] * x cubic_zero = lambda p, x: p[0] * x**3 + p[1] * x**2 + p[2] * x def linFit(x, y,fitfunc): errfunc = lambda p, x, y: fitfunc(p, x) - y ``` Here I want to create a array of zeros. But at this point p isn't defined. so len(p) does not work. ``` init_p = np.array(zeros(len(p))) #bundle initial values in initial parameters p1, success = optimize.leastsq(errfunc, init_p.copy(), args = (x, y)) return p1 ```