返回递归Python函数之外的值

问题描述 投票:0回答:1

这是 8 个皇后拼图的回溯实现。在函数之外返回第一个

perm
有哪些可能的方法。

def can_be_extended_to_solution(perm: List[int]) -> bool:
      """Check if two queens attack each other diagonally.

      Args:
        perm: The permutation of the queens.
    
    Returns:
        True if the permutation can be extended to a solution, False otherwise.
    """
    i = len(perm) - 1
    for j in range(i):
        # Here, we are not using the abs() function because we know that i > j.
        if i - j == abs(perm[i] - perm[j]):
            return False
    return True




def extend(perm: List[int], n:int):
    if len(perm) == n:
        print(perm)
        sys.exit()

    for k in range(n):
        if k not in perm:
            perm.append(k)
            if can_be_extended_to_solution(perm):
                extend(perm, n)
            perm.pop()

我尝试过使用全局变量,但这似乎不起作用。也许是因为拨打了

sys.exit()

python-3.x recursion backtracking
1个回答
0
投票

如果我正确理解了这个问题,那么您希望将变量

perm
的所有值存储在函数之外。如果这是正确的,您可以声明一个列表并将
perm
的每个值附加到列表中。该列表必须在函数外部声明,并且附加必须在函数内部。您还可以在
return
函数中使用
sys.exit()
代替
extend()

l = []

def can_be_extended_to_solution(perm: List[int]) -> bool:
      """Check if two queens attack each other diagonally.

      Args:
        perm: The permutation of the queens.
    
    Returns:
        True if the permutation can be extended to a solution, False otherwise.
    """
    # CHANGED
    l.append(perm)
    i = len(perm) - 1
    for j in range(i):
        # Here, we are not using the abs() function because we know that i > j.
        if i - j == abs(perm[i] - perm[j]):
            return False
    return True




def extend(perm: List[int], n:int):
    if len(perm) == n:
        print(perm)
        # CHANGED
        return

    for k in range(n):
        if k not in perm:
            perm.append(k)
            if can_be_extended_to_solution(perm):
                extend(perm, n)
            perm.pop()
© www.soinside.com 2019 - 2024. All rights reserved.