所以,我有这个练习,我必须从用户输入的坐标找到最近的药房,但我不知道如何。
我有来自每个药房的coodinates的文件,如下:
# Sub-programa
def fazTudo():
dados = open("texto.txt", "r")
linha = dados.readline()
if linha == "":
return "Arquivo de Farmácias está vazio!!!"
else:
for i in range(6):
distancia = []
vetor = dados.readline()
x, y = vetor.split()
distanciaX = x
distanciaY = y
distancia = distanciaX, distanciaY
# Programa Principal
entrada = (input().split(" "))
fazTudo()
当用户输入他的坐标(示例中为“20 88”)时,我应该告诉他最近的坐标。我会写我已经拥有的,但我的代码是巴西葡萄牙语,所以我希望你能帮助我。
{{1}}
答案 0 :(得分:0)
您现在所处的当前阶段似乎正在读取文件的距离。
从那里,你想要做的是找到用户输入的位置与每个药房的位置进行比较。找到X和Y坐标中的最小位移应该可以得到最近的药房。但是因为你想要距离,你需要通过获得绝对值来将位移值转换为距离。
这是我想到的解决方案:
# Find the closest distance to the pharmacies from a text file.
def closest_distance(raw_input_location):
nearest_pharmacy = [0, 0]
user_x_y = raw_input_location.split(" ")
with open("filename.txt") as f:
locations = f.read().splitlines()
if not locations:
return "Pharmacy list is empty!!!"
else:
for index, row in enumerate(locations):
x_y = row.split(" ")
delta_x = abs(int(user_x_y[0]) - int(x_y[0]))
delta_y = abs(int(user_x_y[1]) - int(x_y[1]))
if index == 0:
nearest_pharmacy[0] = delta_x
nearest_pharmacy[1] = delta_y
elif delta_x < nearest_pharmacy[0] & delta_y < nearest_pharmacy[0]:
nearest_pharmacy[0] = delta_x
nearest_pharmacy[1] = delta_y
# Returns the distance required to goto the closest pharmacy
return str(nearest_pharmacy[0]) + " " + str(nearest_pharmacy[1])
# Prints out the closest distance from the inputted location
print(closest_distance("20 88"))