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

โปรแกรม Python นับคู่ Tuple แบบ Bidirectional

ภาพรวม

นับจำนวนคู่ tuple ที่เป็น bidirectional pairs เช่น (45, 67) และ (67, 45) ถือเป็นคู่เดียวกัน

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

my_list = [(45, 67), (11, 23), (67, 45), (23, 11), (0, 9), (67, 45)]
print("รายการ:", my_list)

count = 0
for i in range(len(my_list)):
    for j in range(i + 1, len(my_list)):
        # ตรวจสอบว่า tuple i และ j เป็นคู่กลับกัน
        if my_list[i][0] == my_list[j][1] and my_list[i][1] == my_list[j][0]:
            count += 1

print("จำนวน bidirectional pairs:", count)

ผลลัพธ์

รายการ: [(45, 67), (11, 23), (67, 45), (23, 11), (0, 9), (67, 45)]
จำนวน bidirectional pairs: 3

คำอธิบาย

  • ใช้ nested loop เปรียบเทียบคู่ที่ i < j (กันนับซ้ำ)
  • เงื่อนไข: tuple แรก = (a, b), tuple ที่สอง = (b, a)
  • ในตัวอย่าง: (45,67)-(67,45), (11,23)-(23,11), (67,45) ตัวที่สองกับ (45,67) = 3 คู่

วิธีที่มีประสิทธิภาพมากกว่า (O(n))

from collections import Counter

def count_bidirectional_fast(lst):
    counter = Counter(lst)
    count = 0
    for (a, b), freq in counter.items():
        if a == b:  # (x, x) จับคู่กับตัวเอง
            count += freq * (freq - 1) // 2
        elif a < b:  # กันนับซ้ำ
            count += freq * counter.get((b, a), 0)
    return count

print(count_bidirectional_fast(my_list))  # 3