Count all Occurrences of a Number
In this lesson, we will learn how to count all occurrences of a key in a given array.
We'll cover the following
What does “Count all Occurrences of a Number” mean?
Our task here is to find the number of times a key occurs in an array.
For example:
Number of occurrences of a key
Implementation
def count(array, key) :# Base Caseif array == []:return 0# Recursive case1if array[0] == key:return 1 + count(array[1:], key)# Recursive case2else:return 0 + count(array[1:], key)# Driver Codearray = [1, 2, 1, 4, 5, 1]key = 1print(count(array, key))
Explanation
We need to count the number of times key
occurs in an array. We can do this by checking the first element. If the first element is the specified key
we will be adding to the result, else, we will be adding . After checking the first element pass, remove it, and call the function count
again.
It is easy to implement code if we visualize the solution of the larger problem as the sum of the solution of the smaller tasks.
In this case:
Let’s have a look at the sequence of function calls:
In the next lesson, we will learn how to invert an array.