简体   繁体   中英

8 Queens Python implementation empty lists

def check(a,i):
   n = len(a)
   return not (i in a or
               i+n in [a[j]+j for j in range(n)] or
               i-n in [a[j]-j for j in range(n)]) 

def rsearch(N):
   global a
   global b

   if len(a) == N:
      b.append(a) #<-- this works HERE
      print(a) #<-- this also works HERE
      return True

   z = False
   for i in range(N):
      if check(a,i):
         a.append(i)
         z = rsearch(N) or z
         del a[-1]
   return z


a = []
b = []
rsearch(8)
print(a) #<-- empty list ??
print(b) #<-- list of 92 empty lists ?? ??
print(len(b)) #<-- returns 92

So I have this implementation for the 8 Queens problem written in Python, it works but I'm having some issues formatting. in my len(a) == N check I print the solution list, works fine, I append the solution list to another list, b, which works fine in that moment. But the final print(a) gives back an empty list, and print(b) gives back a list containing 92 empty lists, it found every solution but they're all empty. Anyone know what I'm doing wrong , why they're empty?

As to why a is empty: You perform a.append(i) followed by del a[-1] . This effectively appends an element to a and then removes it again. The total count will remain zero therefore.

As to why b only contains empty lists: You append a to b ( b.append(a) ) and hence b stores references to the list pointed to by a . Since a is an empty list, b contains 92 (similar) references to the same empty list a . If at all you should append a copy of a , eg b.append([x for x in a]) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM