Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

numpy (which is inspired by Matlab which is inspired by APL) does indeed have a count_nonzero function, which is intended to be used in situations like this. Unfortunately, it (like most of numpy) doesn't work with generators, just array-like objects (aka numpy arrays and python lists), so it has the same memory performance issues as filtering and using len.

If your input was a numpy array to begin with you could skip the array comprehension, and shorten it to numpy.count_nonzero(ages > 17), since numpy automatically broadcasts the comparison operation to each element of the array.



Here, is "broadcasts" like apply or map of functional programming?


Yes, very similar. When performing an operation between an array and a scalar, it is identical to mapping that operation on each element of the array. Broadcasting generalizes this to also handle operations between matrices and vectors, such that the operation with the vector is applied to each row or column of the matrix.


Thank you.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: