How is max supposed to work, especially key.

Albert van der Horst albert at spenarnc.xs4all.nl
Thu Nov 27 12:34:43 EST 2014


In the Rosetta code I come across this part of
LU-decomposition.

def pivotize(m):
    """Creates the pivoting matrix for m."""
    n = len(m)
    ID = [[float(i == j) for i in xrange(n)] for j in xrange(n)]
    for j in xrange(n):
        row = max(xrange(j, n), key=lambda i: abs(m[i][j]))
        if j != row:
            ID[j], ID[row] = ID[row], ID[j]
    return ID

That it's using a cast from boolean to float and using
at the other moment a float as a boolean, suggest that this
code is a bit too clever for its own good, but anyway.

My problem is with the max. I never saw a max with a key.

In my python help(max) doesn't explain the key. It says that
max can handle an iterator (I didn't know that), and you can
pass and optional "key=func", but that's all.

I expect it to be something like
  elements in the iterator are taken into account only if the
  key applied to the iterator evaluates to a True value.

However that doesn't pan out:
"
max(xrange(100,200), key=lambda i: i%17==0 )
102
"

I expect the maximum number that is divisible by 17 in the
range, not the minimum.

Can anyone shed light on this?

Groetjes Albert
-- 
Albert van der Horst, UTRECHT,THE NETHERLANDS
Economic growth -- being exponential -- ultimately falters.
albert at spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst




More information about the Python-list mailing list