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

โปรแกรม Python นับอิลิเมนต์ในลิสต์จนเจอ Tuple


นับจำนวนอิลิเมนต์ในลิสต์จนกว่าจะพบ tuple โดยใช้ isinstance()

ตัวอย่าง

Input: [4,5,6,10,22,33,(1,2,3),11,2,4]
Output: 6

อัลกอริทึม

  1. กำหนดตัวนับ c = 0
  2. วนลูปทุกอิลิเมนต์
  3. ถ้า isinstance(item, tuple) ให้ break
  4. เพิ่ม c ทีละ 1
  5. คืน c

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

def countelement(M):
    c = 0
    for i in M:
        if isinstance(i, tuple):
            break
        c += 1
    return c

A = [4,5,6,10,22,33,(1,2,3),11,2,4]
print(countelement(A))  # 6

ผลลัพธ์

6