In article <mailman.16378.1417111312.18130.python-l...@python.org>, Peter Otten <__pete...@web.de> wrote: >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. > So in that case max doesn't return the maximum (True), but instead something else. Useful as that function may be, it shouldn't have been called max. I don't blame myself for being misled. Groetjes Albert -- Albert van der Horst, UTRECHT,THE NETHERLANDS Economic growth -- being exponential -- ultimately falters. albert@spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst -- https://mail.python.org/mailman/listinfo/python-list