[Tutor] global variables & recursion

alice RobinHood42 at clickta.com
Mon Feb 23 04:48:42 EST 2004


I would like some advice.
Is there a better way of doing this?
Particularly I'm not sure if using global variables is a good idea.

# Euclid's algorithm (greatest common divisor):

def gcd(a,b):
    if (b > a):
       a, b = b, a
    r = a % b
    if (r == 0):
       return b
    else:
       return gcd(b,r)

# Find integers s and t such that as + bt = gcd(a,b):

# global variables (is this bad programming style?)

_eulen = 0  # recursion depth
_rem = []   # list of remainders

def st(a,b):

    global _eulen
    global _rem

    # a should be bigger than b:
    if (b > a):
       a, b = b, a

    # find remainder:
    r = a % b

    if (r == 0):        # finished

       # find s and t:
       s = 1
       t = 1 - (a / b)
       for i in range(_eulen):
           b = _rem.pop()
           a = _rem.pop()
           s,t = t, s - (a/b)*t

       # show results:
       print "gcd(%d,%d) = (%d)(%d) + (%d)(%d) = %d" % (a,b,a,s,b,t,a*s+b*t)

       # reset _eulen and _rem:
       _eulen = 0
       _rem = []

    else:              # not finished.

       # we will need this information later:
       _eulen += 1
       _rem.append(a)
       _rem.append(b)

       # function calls itself:
       st(b,r)





More information about the Tutor mailing list