Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Chương trình Python đếm số lần xuất hiện phần tử trong Tuple


Cho một tuple nhập từ người dùng, nhiệm vụ đếm số lần xuất hiện của một phần tử cho trước trong tuple.

Ví dụ

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

Thuật toán

countoccur(A,x) /* A là mảng và x là phần tử cần đếm */
Bước 1: Dùng biến đếm đếm phần tử trùng.
Bước 2: Duyệt tuple.
Bước 3: So sánh x với từng phần tử.
Bước 4: Nếu khớp thì tăng counter 1.
Bước 5: Trả về counter.

Ví dụ mã

# Chương trình đếm số lần xuất hiện phần tử trong 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))

Kết quả

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