2011-09-22 101 views
0

我的任務是讓距離計算器找到兩個位置之間的距離,我選擇使用Python。Python距離公式計算器

我已經把所有的位置爲座標點,但我需要知道如何通過名字來挑選其中的兩個,然後應用距離公式對他們說:

(sqrt ((x[2]-x[1])**2+(y[2]-[y1])**2) 

不管怎麼說,我不知道需要你寫出所有的東西,只要指向正確的方向。

fort sullivan= (22.2, 27.2) 
Fort william and mary= (20.2, 23.4) 
Battle of Bunker II= (20.6, 22) 
Battle of Brandywine= (17.3, 18.3) 
Battle of Yorktown= (17.2, 15.4) 
Jamestown Settlement= (17.2, 14.6) 
Fort Hancock=(18.1, 11.9) 
Siege of Charleston=(10.2, 8.9) 
Battle of Rice Boats=(14.1, 7.5) 
Castillo de San Marcos=(14.8, 4.8) 
Fort Defiance=(13.9, 12.3) 
Lexington=(10.5, 20.2) 
+1

這是目前沒有有效的Python - 只是一個文本列表。你有什麼代碼,你在哪裏遇到問題?歡迎來到StackOverflow! –

+1

你可以在'math'模塊中找到'sqrt'函數。如果這是作業,請將其標記爲如此。 –

+1

是否有'python'標籤的介紹?這可能是有用的。 – Dave

回答

4

你只需將它們放在一個字典,如:

points = { 
'fort sullivan': (22.2, 27.2), 
'Fort william and mary': (20.2, 23.4) 
} 

,然後從字典中選擇並運行你的東西

x = points['fort sullivan'] 
y = points['Fort william and mary'] 

# And then run math code 
3

使用字典存儲元組:

location = {} 
location['fort sullivan'] = (22.2, 27.2) 
location['Fort william and mary'] = (20.2, 23.4) 

或者你可以最初的語法:

location = { 
    'fort sullivan': (22.2, 27.2), 
    'Fort william and mary': (20.2, 23.4) 
} 

儘管您可能很想從文件中讀取數據。

然後,你可以寫一個距離函數:

def dist(p1, p2): 
    return ((p1[0]-p2[0])**2 + (p1[1]-p2[1])**2)**0.5 

然後,你可以這樣調用:

print dist(
    location['fort sullivan'], 
    location['Fort william and mary'] 
)