2017-10-14 54 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"))