2011-09-22 95 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'] 
)