Sign up ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

Suppose we have a data set, ls=(0.3,1.4,1.6,2.3,3.2,4.7) Find the count of values within intervals of 2. I have to implement this functionality in python whose c code looks like this:

count[length(ls)]={0};
limit=2;
j=0;
for (i=0;i<length(ls);i++)
{
  if(ls[i]<limit)
  count[j]+=1;
  else
  {
  j++;
  i=i-1;
  limit+=2
  }
}

This is our implementation in python

for i in range(limit,10,limit):
    count=0
    for j in ls:
        if j<i+limit and j>i:
            print j,
            count=count+1  
        elif j<i:
            pass
        else:
            break

please suggest an optimized solution

Thanks in advance

share|improve this question

migrated from stackoverflow.com Feb 24 '12 at 13:46

This question came from our site for professional and enthusiast programmers.

1 Answer 1

up vote 3 down vote accepted

"Find the count of values within intervals of 2."

If you want to have it optimized, I would have a look at appropriate library for manipulation of large numerical arrays, such as numpy:

You need the counts of elements within given bins. This is called a histogram.

First define your data:

import numpy as np
ls = np.array((0.3,1.4,1.6,2.3,3.2,4.7))
limit = 2

then create the bins, i.e. [ 0., 2., 4., 6.] in your case (how many elements between 0 and 2, between 2 and 4 and between 4 and 6). The last number in this list is just bigger than the largest number in your ls.

bins = np.arange(0, ls.max()+limit, limit)

now run the histogram function:

hist = np.histogram(ls, bins)

hist returns:

(array([3, 2, 1]), array([ 0.,  2.,  4.,  6.]))

you can interpret these two arrays as:

  • there are 3 elements between 0 and 2
  • there are 2 elements between 2 and 4
  • there is 1 elements between 4 and 6
share|improve this answer
    
Thanks a lot! worked like a charm ! –  Ajay Feb 24 '12 at 9:58

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.