n皇后算法中的python误差



我是Python的新手,所以我只是想构建我已经在C 和Java中构建的所有程序,只是为了熟悉语法。我在N Queen问题中遇到了错误,该问题在C 和Java中完美执行。

这是代码

def place(m , i):
    for j in range(0 , m - 1 ):
        if(x[j] == i or abs(x[j] - i) == abs(j-m)):
            return False
    return True
def nqueen(k , n ):
    for c in range(0, n):
        if( place(k , c) ):
            x[k] = c 
            if ( k == n):
                print(x)
            else:
                nqueen(k + 1 , n)
x = []
num = int(input("Enter the no. of rows and columns: "))
nqueen(0 , num)

num = 4的输出将是:

  • 2 4 1 3
  • 3 1 4 2

遇到的错误是:

  • 追溯(最近的最新电话):

  • 文件" d: p nqueen.py",第18行,在 nqueen(0,num)

  • 文件" d: p nqueen.py",第10行,在nqueen x [k] = c indexError:列表分配索引超出范围

请帮助我。

范围(0,n)产生的列表以零为n-1。您的检查k == n需要为k ==(n-1)。否则,您正在调用x [n],它比您想要的要大。顺便说一句,范围函数默认为0。您可以将范围(M-1)和范围(n)用于与当前相同的结果。

python除非已经分配了元素,否则不允许您访问元素。它可以让您使用append/extend动态生长它,但是要访问特定元素,您实际上必须创建空间:

In [1]: x = []
In [2]: x[0]
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-2-1ae75c28907a> in <module>()
----> 1 x[0]    
IndexError: list index out of range
In [3]: x[0] = 1
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-16-1a754504edbf> in <module>()
----> 1 x[0] = 1    
IndexError: list assignment index out of range
In [4]: x = [0] * 4   
In [5]: x[0]
Out[5]: 0 (0x0)
In [6]: x[0] = 1

(请注意,您也应该在C中执行此操作,但是有时C会让您不安全地逃脱,不确定Java为什么会让您这样做)。

其他选项是使用附录进行迭代:

x = []
for entry in some_list:
     x.append(processed_value(entry))

或使用具有其他缺点的字典,但也可以用作稀疏数组。如果您需要默认读取功能,则可以使用defaultDict:

In [8]: d1 = {}    
In [9]: d1[0] = 1    
In [10]: d2 = {}
In [11]: d2[0]
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-11-8d722d66aade> in <module>()
----> 1 d2[0]
KeyError: 0
In [12]: from collections import defaultdict
In [13]: d2 = defaultdict(int)
In [14]: d2[0]
Out[14]: 0 (0x0)

要在python中固定长度列表,您必须使用

之类的东西

x = [None] * numx = [0] * num

另外, range(0,n)0 to n-1 incypuse中迭代,因此在 place函数中,您应该使用 for j in range(0 , m )

除此之外,逻辑明智的是您在打印结果列表

之前应该检查if ( k == n-1)而不是if ( k == n)

最新更新