On 1 Dec 2005 05:45:54 -0800, Niels L Ellegaard [EMAIL PROTECTED] wrote:
I just started learning python and I have been wondering. Is there a
short pythonic way to find the element, x, of a list, mylist, that
maximizes an expression f(x).
In other words I am looking for a short version of the
[EMAIL PROTECTED] wrote:
Thanks. In that case, would it be easier to understand(beside the
original iterative loop) if I use reduce and lambda ?
You could try putting them side by side and seeing which is easiest for
someone to understand:
reduce(lambda (mv,mx), (v,x): mv v and (mv,mx) or
[EMAIL PROTECTED] wrote:
...
As while DSU is a very smart way to guard the max compare thing, it is
still being introduced as a way that is not related to the original
problem, i.e. I just want to compare f(x)
And that's why in 2.5 you'll just code max(mylist, key=f) to express
this intent
I just started learning python and I have been wondering. Is there a
short pythonic way to find the element, x, of a list, mylist, that
maximizes an expression f(x).
In other words I am looking for a short version of the following:
pair=[mylist[0],f(mylist[0])]
for x in mylist[1:]:
if f(x)
Niels L Ellegaard wrote:
I just started learning python and I have been wondering. Is there a
short pythonic way to find the element, x, of a list, mylist, that
maximizes an expression f(x).
In other words I am looking for a short version of the following:
pair=[mylist[0],f(mylist[0])]
wrote:
In other words I am looking for a short version of the following:
pair=[mylist[0],f(mylist[0])]
for x in mylist[1:]:
if f(x) pair[1]:
pair=[x,f(x)]
this is already very short, what else you want? May be this :
max(((f(x), x) for x in mylist))
That is first
Duncan Booth wrote:
wrote:
In other words I am looking for a short version of the following:
pair=[mylist[0],f(mylist[0])]
for x in mylist[1:]:
if f(x) pair[1]:
pair=[x,f(x)]
this is already very short, what else you want? May be this :
max(((f(x), x) for x
[EMAIL PROTECTED] wrote:
...
thanks. I don't know what max can or cannot compare.
Just the same things that you can compare with, say, .
I believe in 2.5 max and min will also accept a key= argument (like
sorted etc) to tweak what to compare, so max(thelist, key=f) should then
work (but in
Alex Martelli wrote:
[EMAIL PROTECTED] wrote:
...
thanks. I don't know what max can or cannot compare.
Just the same things that you can compare with, say, .
I believe in 2.5 max and min will also accept a key= argument (like
sorted etc) to tweak what to compare, so max(thelist,