Python program to count occurrences of an element in a tuple

PythonServer Side ProgrammingProgramming

Here given a user input tuple, our task is to count occurrences of a given element in a tuple.

Example

Input : A = [10, 20, 30, 40, 10, 100, 80, 10]
X = 10
Output : 3

Algorithm

countoccur(A,x)
/* A is an array and x is the element to count the number of occurrences */
Step 1: First we use one counter variable which is count the same element.
Step 2: Then traverse the tuple.
Step 3: Then check x with every element of the tuple.
Step 4: If the element is matched with the x, then counter is incremented by 1.
Step 5: Return counter variable.

Example Code

# Program to count occurrences of an element in a tuple

def countoccur(A, x):
c = 0
for i in A:
if (i == x):
c = c + 1
return c

# Driver Code
A=list()
n1=int(input("Enter the size of the List ::"))
print("Enter the Element of List ::")
for i in range(int(n1)):
k=int(input(""))
A.append(k)
n=int(input("Enter an element to count number of occurrences ::"))
print("Number of Occurrences of ",n,"is",countoccur(A, n))

Output

Enter the size of the List ::6
Enter the Element of List ::
12
23
45
12
89
12
Enter an element to count number of occurrences :12
Number of Occurrences of 12 is 3