[Tutor] global variables & recursion
Alan Gauld
alan.gauld at blueyonder.co.uk
Mon Feb 23 17:06:05 EST 2004
> Particularly I'm not sure if using global variables is a good idea.
Its hardly ever a good idea. Much better to pass them in as
arguments to the function
> def gcd(a,b):
> ...
No probs there
> # global variables (is this bad programming style?)
Usually
> _eulen = 0 # recursion depth
> _rem = [] # list of remainders
>
> def st(a,b):
Change to:
def st(a,b,c,d):
eulen = c
rem = d
# 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,eulen,rem)
That uses the same algorithm but avoids the global variables by
simply passing them in as arguments.
Now as to whether the basic algorithm can be improved, and I think
it can, I'll leave to someone else, like Danny - who seems to
particularly enjoy these little mathematical games... :-)
Alan G.
More information about the Tutor
mailing list