I have this problem where I´m given to list of numbers each list for coordinate X and Y and I have to find which of the coordinates is closest to the first coordinate of the list, for that I have the following code:
import math
list1 = [1, 2, 1, 1]
list2 = [4, 7, 6, 3]
if len(list2) == len(list1):
print ("number of elements does match\n")
else:
print ("number of elements doesnt match\n")
a=1
dist_list = []
for i in range(1, len(list1)):
x1 = list1[0]
y1 = list2[0]
x2 = list1[a]
y2 = list2[a]
dist = abs(math.sqrt((x1-(x2)**2) - (y1-(y2)**2)))
a=a+1
dist_list.append(dist)
print ("distancias:", dist_list, "\n")
for element in iterable:
if element:
return
return False
print(list1[b],",",list2[b], "es la coordenada mas cercana")
# "is the closest coordinate"
In this case, the distances between coordinates show that that coordinate 1,3 is the closest to 1,4.
distancias: [6.48074069840786, 5.656854249492381, 2.23606797749979]
I need to say that here: print(list1[b],",",list2[b], "es la coordenada mas cercana")
I have been searching and found the any()
function and according to Python documentation the way I can recreate the formula is:
def any(iterable):
for element in iterable:
if element:
return True
return False
But I can´t see how to recreate it for me to get the desired result. Also, I must say that for this exercise I can only use for
, in
, while
, sqer, abs and append
.
any()
is useless for this. You have to recreate min()
(or maybe rather numpy.argmin()
)
You have to get first distance at start and compare with all other values and when other value is smaller then keep value and its index.
b = 0 # get first index
b_value = dist_list[0] # get first value
# compare with other distances
for i in range(1, len(dist_list)):
if dist_list[i] < b_value: # if new distance is smaller
b = i # keep new index
b_value = dist_list[i] # keep new value
b = b+1 # because `dist_list[0]` has value for `list1[1]`, not `list1[0]`
(BTW: normally I would use enumerate()
instead of range(len())
but I assume you don't know it)
EDIT: as @Tomerikoo pointed out formula for distance is wrong. It should be:
dist = math.sqrt((x1-x2)**2 + (y1-y2)**2)
Full code
import math
list1 = [1, 2, 1, 1]
list2 = [4, 7, 6, 3]
if len(list2) == len(list1):
print ("number of elements does match\n")
else:
print ("number of elements doesnt match\n")
dist_list = []
x1 = list1[0]
y1 = list2[0]
for i in range(1, len(list1)):
x2 = list1[i]
y2 = list2[i]
#dist = abs(math.sqrt((x1-(x2)**2) - (y1-(y2)**2)))
dist = math.sqrt((x1-x2)**2 + (y1-y2)**2)
dist_list.append(dist)
print ("distancias:", dist_list, "\n")
b = 0
b_value = dist_list[0]
for i in range(1, len(dist_list)):
if dist_list[i] < b_value:
b = i
b_value = dist_list[i]
b = b+1 # because `dist_list[0]` has value for `list1[1]`, not `list1[0]`
print(list1[b],",",list2[b], "es la coordenada mas cercana")
# "is the closest coordinate"