【发布时间】:2011-03-29 22:11:39
【问题描述】:
我目前正在构建一个基于位置的服务,该服务可以为共享汽车的用户计算前往特定活动的路线。为了计算最短距离,需要知道用户之间的行驶距离,因为系统的一个约束条件是每个驾驶员不得超过一定的距离来接载特定的乘客.为了避免为同一条路线调用两次 Google Maps API,我在程序的开头填充了一个字典来存储距离。距离是这样生成的:
def generateDistances(self):
users = self.drivers + self.passengers
for user1 in users:
for user2 in users:
if user1 != user2:
distance = GetDistance(user1.location, user2.location)
self.distances.append({'Start' : user1, 'End' : user2, 'Distance' : distance['Distance']['meters'], 'Duration': distance['Duration']['seconds']})
self.distances.append({'Start' : user1, 'End' : self.destination, 'Distance' : distance['Distance']['meters'], 'Duration': distance['Duration']['seconds']})
GetDistance 方法只是根据它们的纬度和经度从 Google Maps API 获取两个位置之间的路线。然后程序调用以下函数在字典中查找距离:
def getSavedDistance(self, user1, user2):
if user1 == user2:
return 0
for record in self.distances:
if record['Start'] == user1:
if record['End'] == user2:
return record['Distance']
logging.warn("No distance from %s to %s found" % (user1.userid, user2.userid))
但是,我一直在 Google App Engine 上运行它并且运行速度非常慢,正如您可以想象的那样,随着问题规模的增加(即更多用户),运行时间呈指数增长。我想要做的是用每个用户之间的直线距离初始化dict(数学计算,不需要API调用),当系统测试路线的长度时,它会首先测试直线距离。如果直线距离大于最大距离,则路线太长 - 不需要计算实际距离。否则,系统只会看到行驶距离不在字典中,并进行必要的 API 调用以将其放入其中。
所以,我想出了类似这样的方法来初始化距离(请注意,这不起作用,因为我无法将 null 插入到 dict 值中):
def initialiseDistances(self):
users = self.drivers + self.passengers
for user1 in users:
for user2 in users:
if user1 != user2:
self.distances.append({'Start' : user1, 'End' : user2, 'Distance' : null, 'Duration' : null, 'StraightLine' : GetStraightLineDistance(user1.location, user2.location)})
self.distances.append({'Start' : user1, 'End' : self.destination, 'Distance' : null, 'Duration' : null, 'StraightLine' : GetStraightLineDistance(user1.location, self.destination)})
...然后 getSavedDistance 方法可以更改为这样的:
def getSavedDistance(self, user1, user2):
if user1 == user2:
return 0
for record in self.distances:
if record['Start'] == user1:
if record['End'] == user2:
if record['Distance'] == null:
distance = GetDistance(user1.location, user2.location)
record['Distance'] = distance['Distance']['meters']
record['Duration'] = distance['Duration']['seconds']
return record['Distance']
logging.warn("No distance from %s to %s found" % (user1.userid, user2.userid))
这将允许系统仅填充实际使用的距离值,并避免两次调用相同的 API。但是,显然我不能将 null 插入到 dict 值中。有没有人知道我可以在这个字典中插入一些值来告诉我距离没有价值的方法?
谢谢
【问题讨论】:
-
你喜欢任何答案吗?
标签: python google-maps dictionary