A คือรายการที่กำหนด รายการนี้มีสิ่งอันดับที่ซ้อนกัน งานของเราคือนับองค์ประกอบในรายการจนกว่าองค์ประกอบจะเป็นทูเพิล ที่นี่เราใช้ฟังก์ชัน isinstance() ฟังก์ชันนี้มีอ็อบเจ็กต์พารามิเตอร์สองตัว และ classinfo.object จะถูกตรวจสอบ และ classinfo คือคลาส ประเภท หรือทูเพิลของคลาสและประเภท ฟังก์ชันนี้จะคืนค่า จริง หากอ็อบเจ็กต์เป็นอินสแตนซ์หรือคลาสย่อยของคลาส หรือองค์ประกอบใดๆ ของทูเพิล และเท็จ มิฉะนั้น
Input : A=[4, 5, 6, 10,22,33, (1, 2, 3), 11, 2, 4] Output : 6
อัลกอริทึม
Step 1: Given a list. Step 2: Use one counter variable c which is initialized by 0. Step 3: We traverse the list and verify that encountering a tuple or not in our path of count. Step 4: If it’s true then counter will be increased by 1 otherwise false. Step 5: return c
โค้ดตัวอย่าง
# Program to count the items
# until a list is encountered a tuple
def countelement(M):
c = 0
print("RESULT ::>")
for i in M:
if isinstance(i, tuple):
break
c = c + 1
return c
# Driver Code
A = [4, 5, 6, 10,22,33, (1, 2, 3), 11, 2, 4]
print(countelement(A))
ผลลัพธ์
Result ::>6