recursive function: use a global or pass a parameter?

Albert van der Horst albert at spenarnc.xs4all.nl
Sat Jan 17 18:30:04 CET 2015


In article <5e4ccec6-7a00-467d-8cf6-258ab0421c90 at googlegroups.com>,
Tim  <jtim.arnold at gmail.com> wrote:
>I have this type of situation and wonder if I should use a global
>variable outside the recursive function instead of passing the updated
>parameter through.
>
>I want to get a union of all the values that any 'things' key may have,
>even in a nested dictionary (and I do not know beforehand how deep the
>nesting might go):
>
>d = {'things':1, 'two':{'things':2}}
>
>def walk(obj, res):
>    if not hasattr(obj, 'keys'):
>        return set(), set()
>
>    if 'things' in obj:
>        res.add(obj['things'])
>
>    for k in obj:
>        walk(obj[k], res)
>
>    return res
>
>walk(d, set()) # returns {1, 2}
>
>Is it better to use a global to keep track of the values or does it even matter?

Neither. You shouldn't pass superfluous parameters, and you shouldn't
abuse globals.

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.
E.g.

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

>
>thanks,
>--Tim

Groetjes Albert
-- 
Albert van der Horst, UTRECHT,THE NETHERLANDS
Economic growth -- being exponential -- ultimately falters.
albert at spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst




More information about the Python-list mailing list