#Program that will load 2 arrays. ELements of the first array are coordinates X. and#the elements of the second array are coordinates Y of a point on a plane.# find the point and print the index of coordinates of the point which is the closest to the#starting point, coordinate 0,0.
import math
i = 0
X = [3,32,15,43,5,22,90,1]
Y = [3,32,15,43,5,22,90,1]
min = math.sqrt(X[0])**2 + math.sqrt(Y[0])**2
while i < len(X):
U = math.sqrt(X[i])**2 + math.sqrt(Y[i])**2
if U < min:
min = U
else:
min = min
i = i + 1
mindex = X.index(min)
print(min)
print(mindex)
so basically the coordinates should be 1,1 since that is the shortest distance from the nul-point with the distance D = 2.But how do I also print the index of that element 1. With the index being 7
Edit: in python
Here you go:
import math
X = [3, 32, 15, 43, 5, 22, 90, 1]
Y = [3, 32, 15, 43, 5, 22, 90, 1]
# calculate distances using list comprehension
distances = [math.sqrt(x) ** 2 + math.sqrt(y) ** 2 for x, y in zip(X, Y)]
# find minimal distance
min_distance = min(distances)
# find index of minimal index
min_distance_index = distances.index(min_distance)
print(min_distance, min_distance_index) # Output: 2.0 7
Just a heads up, you got the wrong formula for euclidean distance. Your formula comes down to x + y
if they're both positive, otherwise you get an error. The actual formula is math.sqrt(x ** 2 + y ** 2)
From the phrasing of your question it sounds like you only want to print the index, in which case the following is enough
import math
X = [3,32,15,43,5,22,90,1]
Y = [3,32,15,43,5,22,90,1]
min_index = min(range(len(X)), key=lambda i: math.sqrt(X[i] ** 2 + Y[i] ** 2))
print(min_index)
Super easy, barely an inconvenience.
>>> min(range(len(X)), key=lambda i: X[i] + Y[i])
7
(No idea what you think squaring square roots achieves, so I removed that.)
check this:
import math
i = 0
X = [3,32,15,43,5,22,90,1]
Y = [3,32,15,43,5,22,90,1]
min = math.sqrt(X[0])**2 + math.sqrt(Y[0])**2
idx = 0
while i < len(X):
U = math.sqrt(X[i])**2 + math.sqrt(Y[i])**2
if U < min:
min = U
idx = i
i = i + 1
print(min)
print(idx)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.