why 'lambda' and 'reduce'?

Steven Taschuk staschuk at telusplanet.net
Thu Jun 12 19:09:37 EDT 2003


Quoth Anand Pillai:
> Manuel Garcia <news at manuelmgarcia.com> wrote:
  [...]
> > print (lambda p:p[0]+'.'+p[1:])(
> >     str((lambda(x,y,t,a):2L*x*x//a)(
  [...]
> This almost qualifies for an "obfuscated" code winner! ;-)

In my opinion, the obfuscations are of mixed quality; while it is
obfuscated, it is not very artistically obfuscated (if I may use
such a phrase).

The algorithm proper (as opposed to its presentation) is quite
direct, hardly obfuscated at all.  Its structure can be seen
clearly in the last equation on
    <http://www.mathpages.com/home/kmath425/kmath425.htm>
The arithmetic-geometric mean algorithm is nearly direct from its
defining recurrence
      x[0] = a                      y[0] = b
    x[n+1] = (x[n] + y[n])/2      y[n+1] = sqrt(x[n]*y[n])
and sqrt(n) is calculated simply by iterating x <- average(x, n/x).

The only real algorithmic obfuscation is the overzealous use of
the geometric mean function.  (For example, rather than simply
multiply x and y, the code computes the geometric mean of xy/F and
F, then squares it.)  It's a nice idea, but sadly, once the
geometric mean function itself is understood, the confusion
evaporates.

The use of reduce to implement recurrences is clever, though; note
that the list argument's elements are immaterial.

The extensive use of the assignment-to-lambda rewrite (for
example, rather than
    x = compute_x()
    return x**2
the code would have
    return (lambda x: x**2)(compute_x())
) does make the code unreadable, but poses no challenge to the
reverse engineer.

(It prints the first 5000 digits of pi, by the way.  At least, it
seems to.  The first thirty digits are right, at least, and the
algorithm is based on a sound plan.  The only question is whether
the arithmetic error and hardcoded recurrence-iteration limits
affect more than ten digits (which is what the code allows for).
Determining *that* would require someone who actually knows
something about numerical analysis, which I do not.)

-- 
Steven Taschuk                               staschuk at telusplanet.net
"[T]rue greatness is when your name is like ampere, watt, and fourier
 -- when it's spelled with a lower case letter."      -- R.W. Hamming





More information about the Python-list mailing list