Recursive function affecting a variable

I have a recursive function to count the number of ways that 8 queens can fit on an 8x8 chessboard without crossing each other (for a class). It works well and gives the correct permutations, an interesting thing happens when I have a program trying to count the number of answers - it constantly returns the counter to zero. When I manually count the permutations of 92 (which is correct).

def can_be_extended_to_solution(perm):
    i = len(perm) - 1
    for j in range(i):
        if i - j == abs(perm[i] - perm[j]):
            return False
    return True

def extend(perm,count, n):
    if len(perm)==n:
        count=count+1
        print "cycle counter= ",count
        print(perm)

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

extend(perm = [], count=0, n = 8)
+4
source share
1 answer

, count. count , , count = count + 1, count , .

( extend 92).

def can_be_extended_to_solution(perm):
    i = len(perm) - 1
    for j in range(i):
        if i - j == abs(perm[i] - perm[j]):
            return False
    return True


def extend(perm, count, n):
    if len(perm) == n:
        count = count + 1
        print("cycle counter= " + str(count))
        print(perm)

    for k in range(n):
        if k not in perm:
            perm.append(k)
            if can_be_extended_to_solution(perm): # if it works
                count = extend(perm, count, n)
            perm.pop()
    return count

print(extend(perm=[], count=0, n=8))
+2

Source: https://habr.com/ru/post/1686701/


All Articles