Ram shifted to a new place recently. There are multiple schools near his locality. Given the co-ordinates of Ram P(X,Y) and schools near his locality in a nested list, find the closest school. Print multiple coordinates in respective order if there exists multiple schools closest to him. Write a function closestSchool that accepts (X ,Y , L) where X and Y are co-ordinates of Ram's house and L contains co-ordinates of different school.
Distance Formula(To calculate distance between two co-ordinates): √((X2 - X1)² + (Y2 - Y1)²)
where (x1,y1) is the co-ordinate of point 1 and (x2, y2) is the co-ordinate of point 2.
Input:
X, Y (Ram's house co-ordinates)
N (No of schools)
X1 Y1
X2 Y2
.
.
.
X6 Y6
Output:
Closest pont/points to X, Y
Python Code:
def closestSchool(x, y, L):
min_distance = float('inf')
closest_schools = []
for school in L:
distance = ((x - school[0]) ** 2 + (y - school[1]) ** 2) ** 0.5
if distance < min_distance:
min_distance = distance
closest_schools = [school]
elif distance == min_distance:
closest_schools.append(school)
for school in closest_schools:
print(school)
x, y = map(int, input().split())
n = int(input())
L = []
for i in range(n):
l = list(map(int, input().split()))
L.append(l)
closestSchool(x, y, L)
Explanation:
This is a Python program that asks the user for input and then calls the closestSchool
function with the input values. Here's a step-by-step explanation of how it works:
The program first asks the user to enter the co-ordinates of Ram's house (x, y) as space-separated integers using the
input()
function and themap()
function to convert the input values to integers.The program then asks the user to enter the number of schools (n) as an integer using the
input()
function.The program creates an empty list
L
to store the co-ordinates of the schools.The program loops
n
times and asks the user to enter the co-ordinates of each school as space-separated integers using theinput()
function and themap()
function to convert the input values to integers. The program then appends the co-ordinates to theL
list.The program calls the
closestSchool
function with the co-ordinates of Ram's house (x
,y
) and the list of schools (L
) as arguments.The
closestSchool
function finds the closest school(s) to the co-ordinates of Ram's house using the distance formula and prints the result.
So this program takes input from the user, passes it to the closestSchool
function, and then prints the output.
No comments:
Post a Comment