计算元组中元素出现次数的 Python 程序
这里给定一个用户输入元组,我们的任务是计算元组中给定元素的出现次数。
示例
Input : A = [10, 20, 30, 40, 10, 100, 80, 10]
X = 10
Output : 3算法
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.
示例代码
#计算元组中元素出现次数的程序
def countoccur(A, x):
c = 0
for i in A:
if (i == x):
c = c + 1
return c
#驱动程序代码
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))输出结果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