- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Number of Boomerangs in Python
Suppose we have n points in the plane that are all pairwise distinct. Now a "boomerang" is a tuple of points like (i, j, k) such that the distance between i and j is the same as the distance between i and k. We have to find the number of boomerangs.
So, if the input is like [[0,0],[1,0],[2,0]], then the output will be 2, as two boomerangs are [[1,0],[0,0],[2,0]] and [[1,0],[2,0],[0,0]].
To solve this, we will follow these steps −
counter_of_boomerangs := 0
for each point_1 in points array, do
x1, y1 = point_1
define a map called distance_count_dict
for each point_2 in points array, do
x2, y2 = point_2
diff_x := x2 - x1
diff_y := y2 - y1
dist := diff_x^2 + diff_y^2
distance_count_dict[ dist ] := distance_count_dict[ dist ] + 1
for each d in distance_count_dict −
n := distance_count_dict[d]
counter_of_boomerangs := counter_of_boomerangs + n * (n - 1)
return counter_of_boomerangs
Example
Let us see the following implementation to get better understanding −
from collections import defaultdict class Solution: def numberOfBoomerangs(self, points): counter_of_boomerangs = 0 for point_1 in points: x1, y1 = point_1 distance_count_dict = defaultdict( int ) for point_2 in points: x2, y2 = point_2 diff_x = x2-x1 diff_y = y2-y1 dist = diff_x ** 2 + diff_y ** 2 distance_count_dict[ dist ] += 1 for d in distance_count_dict: n = distance_count_dict[d] counter_of_boomerangs += n * (n-1) return counter_of_boomerangs ob = Solution() print(ob.numberOfBoomerangs([[0,0],[1,0],[2,0]]))
Input
[[0,0],[1,0],[2,0]]
Output
0