recursive function: use a global or pass a parameter?
rosuav at gmail.com
Sat Jan 17 20:27:22 CET 2015
On Sun, Jan 18, 2015 at 4:30 AM, Albert van der Horst
<albert at spenarnc.xs4all.nl> wrote:
> The proper technique is make the global local to the normal subroutine,
> then make the subroutine with those parameters you don't want to see
> also local to that subroutine.
> def fib(n):
> ' return the n-th Fibonacci number '
> a,b = 0,1
> def fib1(ap,bp):
> ' for f_n,f_n+1, return f_n+1,f_n+2 '
> return bp,ap+b
> for i in xrange(n):
> a,b = fib1(a,b)
> return a
That's a fairly useless use of a nested function... you could in-line
it without any effort at all:
a,b = 0,1
for i in xrange(n):
a,b = b,a+b
Even in the OP's example, where the inner function needs to call
itself recursively, it doesn't need to be a closure; a simple
out-of-line helper function does work (and has already been suggested;
Gregory was, I think, first). In my opinion, it's not materially
different from having an argument with a default.
More information about the Python-list