Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the idiomatic way of counting the number of elements matching predicate?

Is there a better way to count the number of elements for which the predicate function is true, other than this:

PredCount[lst_, pred_] := Length@Select[lst, pred];

I'm asking because it seems inefficient to construct a subset of lst with Select[], and because Count[] only works with patterns. In my use case, the function PredCount is called many times with a large lst.

like image 641
Gleno Avatar asked Dec 16 '22 01:12

Gleno


2 Answers

You can often do this by turning your predicate into a pattern with a condition. For example:

Count[list, x_/;x>5]

would count the number of elements in list which are greater than 5.

like image 119
High Performance Mark Avatar answered Apr 26 '23 23:04

High Performance Mark


I would use PatternTest

PredCount = Count[#, _?#2] &;

PredCount[Range@30, PrimeQ]
(*out*) 10

This pattern is simple enough that you might use Count directly.

like image 36
Mr.Wizard Avatar answered Apr 27 '23 00:04

Mr.Wizard