GCD in standard library?
Andrew Bennetts
andrew-pythonlist at puzzling.org
Thu Mar 13 05:22:02 EST 2003
On Wed, Mar 12, 2003 at 10:44:35PM -0500, Jp Calderone wrote:
> On Wed, Mar 12, 2003 at 08:08:18PM -0700, Steven Taschuk wrote:
> >
> > I for one haven't needed this in Python yet, but if I did I'd do
> > it this way:
> > def gcd(a, b):
> > while b:
> > a, b = b, a % b
> > return abs(a)
> > which (1) avoids the unnecessary recursion, (2) gives the right
> > answer for zero operands, and (3) gives a predictable and
> > defensible, if not obviously right, answer for negative operands.
>
> FWIW, tuple packing/unpacking is wasting time in that loop. I'd do it
> with a temporary variable, even though it looks nicer without one :)
Nah, leave it as is, and let Psyco optimise it for you :)
-Andrew.
More information about the Python-list
mailing list