我目前正在编写一种代码,通过为我提供列表中可以采用的每条路径来查找从一个机场到另一个机场的路径。机场在字典中,如下所示:
airports = {"ATL": {"lat": 33.6407, "lon": -84.4277},#and so on
我已经实现了另一个代码来计算两个地方的距离,称为半正矢。各个航班的距离不应超过我通过参数给出的距离。更多信息位于我的代码的文档字符串中。
def find_paths(airports: dict, start: str, end: str, max_distance: int, path=None):
"""
Generates all possible paths between two airports within a given maximum distance.
This function is a generator that yields all the paths from a starting airport to an ending airport. Each path is constrained by a maximum distance between consecutive airports in the path. The function uses recursion and backtracking to explore all potential paths.
Args:
airports (dict): A dictionary where keys are airport codes and values are dictionaries containing 'lat' and 'lon' keys for latitude and longitude.
start (str): The airport code representing the starting airport.
end (str): The airport code representing the destination airport.
max_distance (float): The maximum distance allowed between two consecutive airports in the path.
path (list): The current path being explored. Defaults to an empty list.
Yields:
list: A list of airport codes representing a valid path from start to end within the maximum distance constraints.
"""
if path is None:
path = [start]
if path==end:
yield path
for i in airports:
if i not in path:
distance = haversine((airports[start]["lat"],airports[start]["lon"]),((airports[i]["lat"],airports[i]["lon"])))
if distance<=max_distance:
yield from find_paths(airports, i, end, max_distance, path+[i])
for i in find_paths(airports,"ATL","SIN",5000):
print(i)
我认为递归当前正在每次函数递归时生成一个生成器。所以我尝试不使用递归来做到这一点,但我不知道该怎么做。我尝试在产量之后不使用“from”,但后来我只得到了 Generator 对象,而不是我想要的列表。
当起始机场与结束机场相同时,递归应该结束。
改变:
if path==end:
yield path
for i in airports:
...
至:
if start == end:
yield path
else:
for i in airports:
...