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

Number of Boomerangs ใน Python: นับจำนวนบุเมรังจากจุดบนระนาบ

ได้ n จุดบนระนาบ (ไม่ซ้ำกัน) "บุเมรัง" คือ 3 จุด (i,j,k) ที่ระยะห่าง i-j = i-k นับจำนวนบุเมรังทั้งหมด (ลำดับสำคัญ)

ตัวอย่าง

[[0,0],[1,0],[2,0]] → บุเมรัง: ([1,0],[0,0],[2,0]) และ ([1,0],[2,0],[0,0]) → 2

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

  1. วนแต่ละจุดเป็น i (จุดศูนย์กลาง)
  2. คำนวณระยะยกกำลังสองไปยังจุดอื่นทั้งหมด เก็บจำนวนใน dict
  3. แต่ละระยะที่มี n จุด → เพิ่ม n * (n-1) บุเมรัง
  4. รวมทั้งหมด

การติดตั้งใน Python

from collections import defaultdict

class Solution:
    def numberOfBoomerangs(self, points):
        ans = 0
        for x1, y1 in points:
            dist_count = defaultdict(int)
            for x2, y2 in points:
                dx, dy = x2 - x1, y2 - y1
                dist_count[dx*dx + dy*dy] += 1
            for n in dist_count.values():
                ans += n * (n - 1)
        return ans

ob = Solution()
print(ob.numberOfBoomerangs([[0,0],[1,0],[2,0]]))  # 2

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

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