[prev in list] [next in list] [prev in thread] [next in thread] 

List:       python-list
Subject:    Re: How is max supposed to work, especially key.
From:       Peter Otten <__peter__ () web ! de>
Date:       2014-11-27 18:01:21
Message-ID: m57ou2$lom$1 () ger ! gmane ! org
[Download RAW message or body]

Albert van der Horst wrote:

> 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?

Given a function f() max(items, key=f) returns the element of the `items` 
sequence with the greatest f(element), e. g. for

max(["a", "bcd", "ef"], key=len)

the values 1, 3, 2 are calculated and the longest string in the list is 
returned:

>>> max(["a", "bcd", "ef"], key=len)
'bcd'

If there is more than one item with the maximum calculated the first is 
given, so for your attempt

max(xrange(100,200), key=lambda i: i%17==0 )

the values False, False, True, False, ... are calculated and because

>>> True > False
True

the first one with a True result is returned.

-- 
https://mail.python.org/mailman/listinfo/python-list
[prev in list] [next in list] [prev in thread] [next in thread] 

Configure | About | News | Add a list | Sponsored by KoreLogic