Programming intro book ch1 and ch2 (Windows/Python 3) - Request For Comments

Mensanator mensanator at aol.com
Fri Dec 18 18:26:05 EST 2009


> The second deviation is that since most names are constants,

Really? Does that mean you don't use literals, to save the time
required to convert them to integers? Isn't that done at compile
time?

So, instead of doing the Collatz Conjecture as

while a>1:
  f = gmpy.scan1(a,0)
  if f>0:
    a = a >> f
  else:
    a = a*3 + 1

You would do this?

zed = 0
one = 1
two = 2
twe = 3
while a>one:
  f = gmpy.scan1(a,zed)
  if f>zed:
    a = a >> f
  else:
    a = a*twe + one

Does this really save any time?

Now, it's a different story if you're using the gmpy module.
You DON'T want to use literals in loops involving gmpy, because
they would have to be coerced to .mpz's on every pass through the
loop.

In that case, you DO want to use constants as opposed to literals:

ZED = gmpy.mpz(0)
ONE = gmpy.mpz(1)
TWO = gmpy.mpz(2)
TWE = gmpy.mpz(3)
while a>ONE:
  f = gmpy.scan1(a,0) # int used here, so it can be a literal
  if f>ZED:
    a = a >> f
  else:
    a = a*TWE + ONE

And yes, the time savings can be tremendous, especially when 'a'
has over 50,000 decimal digits.

. I do not follow PEP
> 8's recommendation to use uppercase names of constants. In fact almost no Python
> code does,

Mine does when I use gmpy. Otherwise, the notion that "most names
are constants" is generally false.



More information about the Python-list mailing list