[Tutor] Re: Ugly python one-liner !

Derrick 'dman' Hudson dman@dman.ddts.net
Tue, 9 Jul 2002 22:57:29 -0500

Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Mon, Jul 08, 2002 at 10:59:30PM +0530, Prahlad Vaidyanathan wrote:

|     I was again playing around with the matrix module I have been
| working on recently, and I found I could write this absolutely perl-ish
| one-liner to compute the one-norm of the matrix.

import operator

|     def one_norm (self) :
|         """The sum of the elements in different rows of each column
|         is computed, and the maximum of these values is said to
|         be the one-norm of the Matrix.
|         """
          return max([reduce(operator.add,
|                     [abs(self[r,c]) for r in range(self.rows)])
|                         for c in range(self.columns)])

|     Between map(), reduce() and list comprehension, I have finally
| succeeded in making python look scary :-)

Yep.  But you don't need that lambda in there -- the operator module
already has an add function for just that purpose :-).  You also don't
need the backslashes -- python knows to continue because you haven't
close the parenthesis.


Microsoft is to operating systems & security ....
                                     .... what McDonald's is to gourmet coo=

Content-Type: application/pgp-signature
Content-Disposition: inline

Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org