无论如何,要改变我的递归函数返回一个值,是没有全局变量?

2024-04-29 07:10:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我只学了一个月的Python。这是一个递归函数,我为我的Pygame寻找正确的方法在一个多边形没有撤退。这里是一个五边形,(0,1,2,3,4)是顶点数。你知道吗

但是,此代码使用两个全局变量:

last_poses = {}
route_all = []

这意味着每次调用它时都必须初始化这两个变量。我也尝试返回所有可用的路线,但它没有正常工作。你知道吗

这个结果来自全局变量,它是正确的:

[{0: 0, 1: 4, 2: 3, 3: 2, 4: 1, 5: 0}, {0: 0, 1: 4, 2: 3, 3: 2, 4: 1, 5: 0}]

此结果来自返回值:

[{0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 0}]

我的问题是返回没有全局变量的正确值。谁能帮我解决这个问题,我真的很感激。你知道吗

legal_action = ((4,1),(0,2),(1,3),(2,4),(0,3))

def route_cal(start_pos, steps):
    global last_poses,route_all
    last_poses[steps] = start_pos
    steps -= 1
    dest_all = list(legal_action[start_pos])

    if len(last_poses) >= 2:
        for i in dest_all:
            if i == last_poses[steps+2]:
                dest_all.remove(i)
    if steps > 0:
        for pos in dest_all:
            # route_cal(pos,steps)
            return route_cal(pos,steps)
    elif steps == 0:
        last_poses[steps] = dest_all[0]
        route_all.append(last_poses)
        return route_all
    # return route_all

last_poses = {}
route_all = []
# route_cal(0, 5)
# print route_all

routelines = route_cal(0,5)
print routelines

Circuit of my game


Tags: posforreturnifactionallstepsroute
3条回答

你有一些选择。一个其中一个使用可选参数。看起来可以使用route\u all作为可选参数。你知道吗

例如

def route_cal(start_pos, steps, route_all = {}):

请记住,可选参数初始化一次(第一次调用函数时)。你知道吗

另一种方法是去掉dest\u all和last\u poses,只使用一个变量route\u all,并将到达多边形某个点的所有人附加到该变量上,并且只返回该点。你知道吗

return [route_all] + [recursive_call_here]

您还可以考虑不使用您的legal\u actions变量,并根据需要创建“neighbors”值,具体取决于您所处的步骤号。你知道吗

还有其他方法可以将问题最小化,我建议将此问题移到Code Review部分,以便更深入地了解代码。例如,我会尽量避免使用如此多的循环,而是使用一个公式,在递归每一步时计算“邻居”。另外,通过确保您不访问它不存在的内容来防止到达索引超出范围异常和/或KeyError异常。你知道吗

与我之前的评论一致,这里有一个遍历多边形的简单迭代方法。它似乎给出了您指定的内容,而不使用全局变量甚至递归。你只需要这些吗?你知道吗

def route_cal(start_node, move_list):
    # For each step in the circuit
    here = start_node
    path = [here]
    for step in range(len(move_list)):
        # Find any legal move to an adjacent vertex
        dest = move_list[here]
        for here in dest:
            if here not in path:    # Don't repeat a vertex
                path.append(here)
                break
    path.append(start_node)

    # Now that we've found the full circuit, build a dictionary in each direction
    path_len = len(path)
    forward = {n: path[n] for n in range(path_len)}
    reverse = {n: path[path_len-n-1] for n in range(path_len)}
    return [forward, reverse]


legal_action = ((4,1), (0,2), (1,3), (2,4), (0,3))
print route_cal(0, legal_action)

最简单的答案是使用非局部而不是全局。这是相同的处理,但是变量在父范围而不是全局范围内。你知道吗

但是,对于您的示例,该函数的父作用域似乎是全局作用域,因此不会更改任何内容。你知道吗

更正确但更困难的答案是,如果您想摆脱外部变量的使用,您必须要么将值作为参数传递到函数中,要么返回一个包含当前全局变量和原始返回变量的元组。你知道吗

This这个问题可能会帮助你开始。你知道吗

相关问题 更多 >