1

This is a backtracking implementation of the 8 queens puzzle. What the possible ways to return the first perm outside of the function.

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()

I have tried using a global variable but that does not seem to work. Perhaps because a call is made to sys.exit().

OmegaO333
  • 52
  • 9
Devang
  • 43
  • 1
  • 6
  • I'm not sure it's quite a duplicate, but this question is closely related to [this canonical question](https://stackoverflow.com/questions/11356168/return-in-recursive-function). – Blckknght Jun 03 '23 at 01:46

1 Answers1

0

If I'm understanding the question correctly, you want all the values of the variable perm stored outside the functions. If this is correct, you can declare a list and append each value of perm to the list. The list will have to be declared outside the function and the appending must be inside.

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)
        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()
OmegaO333
  • 52
  • 9