Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

โปรแกรม Python นับจำนวนครั้งที่อิลิเมนต์ปรากฏใน Tuple


นับจำนวนครั้งที่อิลิเมนต์เฉพาะปรากฏใน tuple ที่ผู้ใช้ป้อน

ตัวอย่าง

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

อัลกอริทึม

  1. กำหนดตัวนับ c = 0
  2. วนลูปทุกอิลิเมนต์ใน tuple
  3. ถ้าตรงกับ x ให้เพิ่ม c
  4. คืน c

โค้ดตัวอย่าง

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

A = []
n = int(input("Enter the size of the List: "))
print("Enter the Elements:")
for _ in range(n):
    A.append(int(input()))
x = int(input("Enter element to count: "))
print("Number of Occurrences of", x, "is", countoccur(A, x))

ผลลัพธ์

Enter the size of the List: 6
Enter the Elements:
12
23
45
12
89
12
Enter element to count: 12
Number of Occurrences of 12 is 3