...

/

Count All Occurrences of a Number

Count All Occurrences of a Number

In this lesson, we will learn how to count all occurrences of a key in a given array.

What does “Count all Occurrences of a Number” mean?

Our task is to find the number of times a key occurs in an array.

For example:

Number of occurrences of a key
Number of occurrences of a key

Implementation

Press + to interact
def count(array, key) :
# Base Case
if array == []:
return 0
# Recursive case1
if array[0] == key:
return 1 + count(array[1:], key)
# Recursive case2
else:
return 0 + count(array[1:], key)
# Driver Code
array = [1, 2, 1, 4, 5, 1]
key = 1
print(count(array, key))

Explanation

We need to count the number of times key occurs in an array. We do this by checking the first element. If the first element is the specified key, we will add 11 to the result. After checking the first element, remove it, and call the function count again.

It is easier to implement code if we visualize the solution of the larger problem as the sum of the solution to the smaller tasks.

In this case:

countofkeyinarray[0:length1]={1+countofkeyinarray[1:length1]ifarray[0 ...