如何将变量从已定义的函数传递到while循环?

时间:2018-02-13 17:10:05

标签: python n-queens

我正在创建一个解决n皇后问题的程序。我们给出的伪代码如下......

import random
# ask the user for an N value
# generate a candidate NQ solution [random.randint(0,n-1) for x in range(n)]
# define a function to count number of conflicts()
# while number of conflicts in NQ > 0
    # randomize (or improve) NQ
# print NQ
# print number of iterations

到目前为止,这就是我所拥有的......

#ask for n value
n = input("Give me a board dimension: ")
n = int(n)
# generate a candidate NQ solution [random.randint(0,n-1) for x in range(n)]
nq = [random.randint(0,n-1) for x in range(n)]

print(nq)
# define a function to count number of conflicts()
def count_conflicts( nq ):
    for i in range( len(nq)-1):
        for j in range(i+1,len(nq) ):
            if abs(i-j)==abs(nq[i]-nq[j]):
                global conflicts
                conflicts += 1
        return conflicts


#print(conflicts)
x = count_conflicts(nq)
print(x)

# while number of conflicts in NQ > 0
# randomize (or improve) NQ
while (conflicts > 0):
    nq = [random.randint(0,n-1) for x in range(n)]
# print NQ
print(nq)

我一直收到以下错误:

Traceback (most recent call last):
  File "C:/Users/wills/AppData/Local/Programs/Python/Python36-32/lasttry.py", line 25, in <module>
    x = count_conflicts(nq)
  File "C:/Users/wills/AppData/Local/Programs/Python/Python36-32/lasttry.py", line 20, in count_conflicts
    conflicts += 1
NameError: name 'conflicts' is not defined

如何在每次发现冲突时将冲突增加1,以及如何在count_conflicts()函数之外使用该变量?

3 个答案:

答案 0 :(得分:0)

实例化conflict,然后在函数中使用它。

conflicts = 0 # or any other value
def count_conflicts( nq ):
    global conflicts
    for i in range( len(nq)-1):
        for j in range(i+1,len(nq) ):
            if abs(i-j)==abs(nq[i]-nq[j]):
                conflicts += 1
        return conflicts

答案 1 :(得分:0)

确切地说错误是什么,冲突是未定义的。

conflicts = 0放在代码的顶部,并根据需要在适当的位置将其重置为0.

答案 2 :(得分:0)

您应该在for i in range( len(nq)-1):循环之前定义conflict = 0。 += 1运算符将一个值递增1,在您的情况下,该值先前未定义。

此外,您必须正确识别代码,因为您在第一个循环结束之前返回值。