Does Python have equivalent to MATLAB "varargin", "varargout", "nargin", "nargout"?
Peter Otten
__peter__ at web.de
Mon Feb 19 04:25:22 EST 2007
openopt at ukr.net wrote:
> Ok, thx
> But can I somehow determing how many outputs does caller func require?
> for example:
> MATLAB:
> function [objFunVal firstDerive secondDerive] = simpleObjFun(x)
> objFunVal = x^3;
> if nargout>1
> firstDerive = 3*x^2;
> end
> if nargout>2
> secondDerive = 6*x;
> end
>
> So if caller wants only
> [objFunVal firstDerive] = simpleObjFun(15)
> than 2nd derivatives don't must to be calculated with wasting cputime.
> Is something like that in Python?
For a sequence whose items are to be calulated on demand you would typically
use a generator in Python. You still have to provide the number of items
somehow (see the head() helper function).
from itertools import islice
def derive(f, x0, eps=1e-5):
while 1:
yield f(x0)
def f(x, f=f):
return (f(x+eps) - f(x)) / eps
def head(items, n):
return tuple(islice(items, n))
if __name__ == "__main__":
def f(x): return x**6
print head(derive(f, 1), 4)
Peter
More information about the Python-list
mailing list