average?

Carl Banks imbosol at vt.edu
Fri Sep 20 15:10:47 EDT 2002


Mark McEahern wrote:
> I know I can average a sequence like this:
> 
>  def average(seq):
>    return reduce(operator.add(seq) / len(seq))
> 
> Yes, I see that will raise ZeroDivisionError if seq == [].  Aside from that,

Appropriate, I'd say, since the average of a zero-length sequence is
undefined.


> 1.  Is there anything else dumb about the above?

Well, yes; it seems to me you meant this:

    def average(seq):
        return reduce(operator.add,seq)/len(seq)

What I can't figure out is how you got from this to what you
typed. :-)


> 2.  Am I missing a builtin cousin of min, max that would do this for me?

In pure Python, I don't think so.  I would be surprised if the above
function (when typed correctly) isn't the fastest way in pure Python.


-- 
CARL BANKS
http://www.aerojockey.com



More information about the Python-list mailing list