我目前正在编写一种代码,它可以通过在列表中提供我可以采用的每条路径来查找从一个机场到另一个机场的路径.机场在一本词典中,看起来是这样的: airports = {"ATL": {"lat": 33.6407, "lon": -84.4277},#and so on个 我已经实现了另一个代码,它可以计算两个位置之间的距离,称为haverine.各个航班的距离不应该超过我通过参数提供的量.更多信息在我的代码的文档字符串中.

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对象,而不是我想要的列表.

推荐答案

当起始机场与结束机场相同时,找到有效路径,而当路径本身与结束机场相同时,则不会找到有效路径.您还应该通过将搜索放在else块中来避免通过有效路径继续搜索:

更改:

if path==end:
    yield path

for i in airports:
    ...

致:

if start == end:
    yield path
else:
    for i in airports:
        ...

Python相关问答推荐

Python:根据创建时间合并两个收件箱

如何防止Plotly在输出到PDF时减少行中的点数?

在matplotlib动画gif中更改配色方案

在Python中为变量的缺失值创建虚拟值

如何根据日期和时间将状态更新为已过期或活动?

如何让 turtle 通过点击和拖动来绘制?

线性模型PanelOLS和statmodels OLS之间的区别

TARete错误:类型对象任务没有属性模型'

Pystata:从Python并行运行stata实例

SQLGory-file包FilField不允许提供自定义文件名,自动将文件保存为未命名

为什么我的Python代码在if-else声明中的行之前执行if-else声明中的行?

如何找到满足各组口罩条件的第一行?

如何使用根据其他值相似的列从列表中获取的中间值填充空NaN数据

Telethon加入私有频道

在Mac上安装ipython

如何获取numpy数组的特定索引值?

Godot:需要碰撞的对象的AdditionerBody2D或Area2D以及queue_free?

cv2.matchTemplate函数匹配失败

为一个组的每个子组绘制,

无论输入分辨率如何,稳定扩散管道始终输出512 * 512张图像