Home > Commands -> Function Commands -> count_if

EXAMPLES ON MY SAGE PAGE - - RandomBetween BinomialTrial and CountIf

Goal: Create a function count_if(list1,p) that returns the number of elements of list1 that have value <= p.

def count_if(list1,p) :
   a=len([j for j in list1 if j<=p])
   return a

Use: c=count_if(x,75)

Result: c=4 for list x=[ 23, 100, 47, -2, 132, 2 ] . This result is of integer type.

Your responsibility: x to be a list of numbers, p to be a number.

Sage commands used:

  • len(list1) yields the length (number of elements) of list1.

Related SageMath Pages: Commands on Lists and Operations with Lists

Keywords: countif, count, if, functions, programming, list, sage