简体   繁体   中英

How do I pass a variable from a defined function to a while loop?

I am creating a program that solves the n queens problem. The pseudocode we were given is as follows...

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

So far this is what I have...

#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)

I keep getting the following error:

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

How do I increase conflicts by 1 each time a conflict is found, and how do I use that variable outside of the count_conflicts() function?

Instantiate conflict , and then use it in the function.

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

It's exactly what the error says, conflicts is undefined.

Put conflicts = 0 at the top of your code and reset it to 0 at an appropriate point if needed.

You should define conflicts = 0 before the for i in range( len(nq)-1): loop. The += 1 operator increments by one the value which, in your case, is not previously defined.

Also you have to ident your code properly, because you are returning the value before the first loop ends.

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