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

โปรแกรมหาผู้ติดตามซ้ำกันจากรายการความสัมพันธ์ใน Python

การหาคู่ที่ติดตามกัน (Mutual Followers)

กำหนดรายการ relations ที่ relations[i] = [a, b] หมายถึง a ติดตาม b หาคู่ที่ติดตามกัน (a ติดตาม b และ b ติดตาม a) คืนค่ารายการคนที่มีความสัมพันธ์แบบสองทาง เรียงลำดับ

อัลกอริทึม

  1. ใช้ Set เก็บคู่ที่เคยเห็น (seen)
  2. ใช้ Set เก็บคำตอบ (ans)
  3. วนลูปแต่ละคู่ (a, b) ใน relations
  4. เพิ่ม (a, b) ลง seen
  5. ถ้า (b, a) อยู่ใน seen แล้ว ให้เพิ่ม a และ b ลง ans
  6. คืนค่า ans ที่เรียงลำดับแล้ว

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

def solve(relations):
    ans = set()
    seen = set()
    for a, b in relations:
        seen.add((a, b))
        if (b, a) in seen:
            ans.add(b)
            ans.add(a)
    return sorted(ans)

relations = [[0, 2], [2, 3], [2, 0], [1, 0]]
print(solve(relations))

ผลลัพธ์

[0, 2]

คำอธิบาย

คู่ (0,2) และ (2,0) มีอยู่ทั้งคู่ → 0 และ 2 ติดตามกัน