[Tutor] Aaagh! Stack arrays!?! calc average

Ben Sherman bensherman at gmail.com
Wed May 2 00:57:22 CEST 2007

```On 5/1/07, John Washakie <washakie at gmail.com> wrote:
>
> It aint pretty! And if I had just walked away, it probably would've
> taken half the time in the morning, but here's what I've come up with
> (any suggestions for improvements, or course are welcome):
>
>     for d in data:
>         w = len(d)
>         if d[0] <= tinit+60:
>             d = column_stack(d)
>             cnt,sum = cnt+1,sum+d
>
>         else:
>             avg = sum/(ones(w)*cnt)
>             tinit,cnt,sum = d[0],0,zeros(n)
>             if init==0:
>                 newData,init = avg,1
>             else:
>                 newData = append(newData,avg,axis=0)
>
>     return newData
>

Sorry my last reply was so terse - I needed to catch a train. :)

So you need to check out a couple of functions - namely sum.

>>> numbers=[1,2,3,4,5]
>>> numbers.append(6)
>>> numbers
[1, 2, 3, 4, 5, 6]
>>> sum(numbers)
21
>>> len(numbers)
6
>>> sum(numbers)/len(numbers)
3

WAIT WAIT hold the phone!?  21/5 is NOT 3!  It's 3.5!  The short story here
is that you have to make on of the numbers a floating point to get the
result to return a float, so do this:

>>> sum(numbers)*1.0/len(numbers)
3.5

So there is our average.  If floor division doesn't make sense to you, you
aren't alone.  This changes in Python 3000.  You can read about floor
division here:
http://www.python.org/doc/2.2.3/whatsnew/node7.html

I don't quite know what your stack is for - it can probably be accomplished
using some slices or other fun stuff.

Good luck, and welcome to python!
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070501/e0ce737a/attachment.htm
```