You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python递归生成器无返回结果问题排查与路径生成代码优化求助

问题分析与解决

首先看代码里的致命错误:

  • 终止条件判断逻辑完全错误:if path==end: 这里path是机场代码组成的列表,end是单个字符串,两者永远不可能相等,导致永远不会触发yield path,自然没有任何输出。

修复后的递归生成器代码

def find_paths(airports: dict, start: str, end: str, max_distance: float, path=None):
    """
    生成两个机场之间所有符合单段航程距离限制的可行路径。
    该生成器函数通过递归回溯探索所有可能路径,每次迭代返回一条有效路径。

    参数:
    airports (dict): 字典,键为机场代码,值包含对应机场的'lat'(纬度)和'lon'(经度)。
    start (str): 起始机场代码。
    end (str): 目标机场代码。
    max_distance (float): 单段航程允许的最大距离。
    path (list): 当前探索的路径,默认空列表(内部初始化)。

    返回:
    list: 一条由机场代码组成的有效路径,满足距离限制。
    """
    if path is None:
        path = [start]
    
    # 修正终止条件:检查路径最后一个机场是否为终点
    if path[-1] == end:
        yield path
        return  # 找到路径后直接返回,避免后续无效遍历
    
    # 遍历所有未在当前路径中的机场
    for airport_code in airports:
        if airport_code not in path:
            # 计算当前路径最后一个机场到候选机场的距离
            current_airport = path[-1]
            distance = haversine(
                (airports[current_airport]["lat"], airports[current_airport]["lon"]),
                (airports[airport_code]["lat"], airports[airport_code]["lon"])
            )
            if distance <= max_distance:
                # 递归探索后续路径,并将结果yield出来
                yield from find_paths(airports, airport_code, end, max_distance, path + [airport_code])

# 调用示例
for path in find_paths(airports, "ATL", "SIN", 5000):
    print(path)

关键修改点说明

  1. 修正终止条件:将path==end改为path[-1] == end,正确判断当前路径是否到达终点。
  2. 优化距离计算逻辑:改用path[-1]获取当前路径的最后一个机场(而非依赖函数参数start),逻辑更清晰,避免递归过程中参数混淆。
  3. 添加return语句:找到终点后直接返回,减少不必要的循环遍历。

非递归实现方案(基于栈的回溯)

如果不想用递归,可以用栈模拟递归过程,每个栈元素存储当前的路径信息:

def find_paths_non_recursive(airports: dict, start: str, end: str, max_distance: float):
    stack = [[start]]
    while stack:
        path = stack.pop()
        current_airport = path[-1]
        
        if current_airport == end:
            yield path
            continue
        
        # 遍历所有未访问的机场
        for airport_code in airports:
            if airport_code not in path:
                distance = haversine(
                    (airports[current_airport]["lat"], airports[current_airport]["lon"]),
                    (airports[airport_code]["lat"], airports[airport_code]["lon"])
                )
                if distance <= max_distance:
                    stack.append(path + [airport_code])

# 调用示例
for path in find_paths_non_recursive(airports, "ATL", "SIN", 5000):
    print(path)

这个非递归版本用栈保存待探索的路径,每次弹出一条路径检查是否到达终点,若未到达则生成所有符合条件的新路径压入栈,实现和递归相同的回溯逻辑。

内容的提问来源于stack exchange,提问作者Terrakotta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 04:31:10