2017-10-14 30 views
-1


所以,我有这个练习,我必须从用户输入的坐标中找到最近的药房,但我不知道如何去做。
我有从各药店的座标,像这样的文件:比较两个阵列,找到最近的结果

300 200 
10 56 
25 41 
90 18 
70 90 
100 50 

而当用户输入自己的坐标(“20 88”中的例子)我应该告诉他从最近的一个坐标。我会写我已经有的,但我的代码是用巴西葡萄牙语,所以我希望你能帮助我。

# 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() 
+1

第一步是计算一个数字,是基于起源各点的距离,然后采取具有最小距离的点。 .. –

回答

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"))