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

โปรแกรมตรวจสอบว่าทุกคนมีเพื่อนอย่างน้อยหนึ่งคนหรือไม่ใน Python

สมมติว่าเรามี n คน แทนด้วยตัวเลข 0 ถึง n-1 และลิสต์ friends ที่แต่ละคู่ [a, b] แสดงว่า a และ b เป็นเพื่อน ตรวจสอบว่าทุกคนมีเพื่อนอย่างน้อย 1 คนหรือไม่

ตัวอย่าง: n = 3, friends = [[0, 1], [1, 2]] ผลลัพธ์ True

ขั้นตอนการแก้ปัญหา

  1. สร้างลิสต์ people ขนาด n เติม 0
  2. สำหรับแต่ละ link ใน friends:
    • people[link[0]] = True
    • people[link[1]] = True
  3. ถ้ามี person ใน people ที่เป็น False คืนค่า False
  4. คืนค่า True

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

class Solution:
    def solve(self, n, friends):
        people = [0 for i in range(n)]
        for link in friends:
            people[link[0]] = True
            people[link[1]] = True
        for person in people:
            if not person:
                return False
        return True

ob = Solution()
n = 3
friends = [[0, 1], [1, 2]]
print(ob.solve(n, friends))  # Output: True

อินพุต / เอาต์พุต

Input: 3, [[0, 1], [1, 2]]

Output: True