maximum() efficency
Mitja Trampus
nun at example.com
Sun Mar 26 13:34:28 EST 2006
Steve R. Hastings wrote:
> I was looking at a Python function to find the maximum from a list.
> The original was more complicated; I simplified it. The built-in max()
> function can replace the simplified example, but not the original.
But you forgot to shuw us the original...
[snip several implementations]
> Of course, it's a little ugly to use a[0] instead of "maxval". And I'm
> trying not to index a list, and here I am indexing another list. So:
>
> def maximum(lst):
> for v in lst:
> try:
> if maxval > v:
> maxval = v
> except NameError:
> maxval = v
> return maxval
>
> In my testing on my computer, the above function works perfectly. Even
> if you do this:
>
>>>> maxval = 100
>>>> print maximum(cmp, [2, 0, 3, 1])
> 3
>
> In other words, you get a NameError in the function even if there is a
> global variable with that name. That's with Python 2.4, however... is
> this function guaranteed to work in all Python versions?
Not 100% sure, but I think yes. People with longer experience in python can answer
definitely. Or you can try it out yourself.
The reason it works is that this:
def f():
print a
a=7; f()
works and prints 7 (global a is used), while this
def f():
print a
a = 12
a=7; f()
does NOT work. Python notices that a is going to get assigned to inside f and treats it as
a local variable. This is also the case with your code. Try out the above examples without
a=7 and notice the different error messages...
> The clear winner was the iterator version. It was much faster than the
> others, and in my opinion it is simpler and easier to understand than any
> of the others.
I would have done it in the same way, but probably without the iterators. I.e., like this:
def maximum(lst):
try: m = lst[0]
except (TypeError, IndexError): raise Exception "Non-sequence or empty sequence given to
maximum")
# (you forgot the above sanity checks in your code.
# not strictly necessary, but nice to have.)
for x in lst:
if x>m: m=x
return m
More information about the Python-list
mailing list