# pls help me with this prog

Tim Roberts timr at probo.com
Sun Oct 21 04:33:01 CEST 2012

```inshu chauhan <insideshoes at gmail.com> wrote:
>
>but i want to calculate it for every 3 points not the whole data, but
>instead of giving me centre for every 3 data the prog is printing the
>centre 3 times...
>
>def main (data):
>    j = 0
>    for  i in data[:3]:
>        while j != 3:
>         centre = CalcCentre(data)
>         j += 1
>         print centre

This loop doesn't do what you think it does.  Think about the problem you
have to solve.  You have a set of data.  You want to operate on the whole
set, 3 points at a time.  What this loop does is grab the first three
points (only), then calculates the center on the entire list three times.

You want something like:

# As long as there is data in the list:
while data:
# Split the list into two parts: first 3 and the rest.
first3, data = data[3:],data[3:]
# Operate on the first three.
print CalcCenter( first3 )

To make it a little more resilient, you might make sure that len(data) is a
multiple of 3, or at least stop when it is shorter than 3.

To be more clever, you can write a function that returns 3 at a time:

def N_at_a_time( iter, n ):
while len(iter) >= n:
yield iter[:n]
iter = iter[n:]

Now you can do this:

def main(data):
for first3 in N_at_a_time(data, 3):
print CalcCenter(first3)
--
Tim Roberts, timr at probo.com
Providenza & Boekelheide, Inc.
```