Question

I have a single-threaded Python module (for resolving the n-Queen problem) with this important method:

def step(self):
    r = Random()        
    poz = r.choice(self.available)   #!!!problem here
    #poz = 9 #this will work
    for p in self.available:
        if self.collision(poz, p):   # this method fails with the usage of random
            self.available.remove(p)
    self.state.queens.append(poz)
    self.debug()
    return True

The method will work fine if I give it a constant value like 9 or anything else, but if I want to use the random function choice to select a value from the available (a list of numbers) the collision() method fails to work properly by missing some.

Here is the collision method if it helps:

def collision(self, a, b):
    x1, y1 = a / self.n, a % self.n
    x2, y2 = b / self.n, b % self.n  
    return x1 == x2 or y1 == y2 or abs(x1 - x2) == abs(y1 - y2) 

Basically it checks if a chess square "b" is attackable by the queen "a"

Was it helpful?

Solution

Found answer here

Remove items from a list while iterating

replaced the iteration with

self.available = [x for x in self.available if not self.collision(poz, x)]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top