[英]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. 因此,对于用Python编写的8 Queens问题,我具有此实现,它可以工作,但是在格式化时遇到一些问题。 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. 在我的len(a) == N
检查是否打印解决方案列表,效果很好,我将解决方案列表附加到另一个列表b,在那一刻效果很好。 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. 但是最终的print(a)
会返回一个空列表,而print(b)
会返回一个包含92个空列表的列表,它找到了每个解决方案,但它们都是空的。 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]
. 至于为什么a
为空:您执行a.append(i)
然后执行del a[-1]
。 This effectively appends an element to a
and then removes it again. 有效地将元素附加到a
,然后再次将其删除。 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
. 至于为何b
只包含空列表:您可以附加a
以b
( b.append(a)
因此b
存储引用到列表中指出a
。 Since a
is an empty list, b
contains 92 (similar) references to the same empty list a
. 由于a
是一个空列表,因此b
包含对同一空列表a
92个(相似)引用。 If at all you should append a copy of a
, eg b.append([x for x in a])
. 如果你要添加的副本a
,如b.append([x for x in a])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.