0

I am developing an N-Queen Simulation using pygame.

class NQ:

    def __init__(self,n):
        self.size = n
        self.columns = [] * self.size
        self.places = 0
        self.backtracks = 0

    def place(self, startRow=0): 
        if len(self.columns) == self.size:

            return self.columns


        else:
            for row in range(startRow, self.size): 
                if self.isSafe(len(self.columns), row) is True: 
                    self.columns.append(row)
                    self.places += 1 
                    return self.place()

            else: 
                lastRow = self.columns.pop()
                self.backtracks += 1 
                return self.place(startRow=lastRow + 1)

    def isSafe(self, col, row): 
        for threatRow in self.columns: 
            threatCol = self.columns.index(threatRow) 
            if row == threatRow or col == self.columns.index(threatRow):
                return False 
            elif threatRow + threatCol == row + col or threatRow - threatCol == row - col:
                return False 
        return True

    def process(n):

        nqueens = NQ(n)
        nqueens.place(0)
        return nqueens.columns

Also I have a pygame procedure in another file to draw chess board which takes a list as input and place them accordingly. If I want to show the movement of queens, how can i pass the list dynamically from the recursivecode procedure so that the exact backtracking procedure is visible. Thank you

2
  • Will the two procedures run simultaneously? If not, you can pickle the list and save it on the disk somewhere and the pygame procedure can unpickle the data and do whatever it does. Commented Nov 20, 2013 at 13:43
  • 1
    Another Python file? Do you mean a module? Perhaps you would simply import the module and call the function? Please clarify if I misunderstood you. Commented Nov 20, 2013 at 14:06

3 Answers 3

1

If you want to know what is going on inside recursive function you can add external function as argument and than you can use it inside recursion to print current state of algorythm or draw queens on chess board.

In example I use show_colums() to print self.columns every time self.place() is running.

file: nq.py

class NQ:

    def __init__(self,n, callback): # added callback
        self.size = n
        self.columns = []
        self.places = 0
        self.backtracks = 0
        self.callback = callback # added callback

    def place(self, startRow=0): 

        self.callback(self.columns) # added callback

        if len(self.columns) == self.size:

            return self.columns

        else:
            for row in range(startRow, self.size): 
                if self.isSafe(len(self.columns), row) is True: 
                    self.columns.append(row)
                    self.places += 1 
                    return self.place()

            else: 
                lastRow = self.columns.pop()
                self.backtracks += 1 
                return self.place(startRow=lastRow + 1)

    def isSafe(self, col, row): 
        for threatRow in self.columns: 
            threatCol = self.columns.index(threatRow) 
            if row == threatRow or col == self.columns.index(threatRow):
                return False 
            elif threatRow + threatCol == row + col or threatRow - threatCol == row - col:
                return False 
        return True

file: main.py

from nq inport NQ

def show_columns(x):
    print "columns:", x

def process(n):
    nqueens = NQ(n, show_columns)
    nqueens.place(0)        
    return nqueens.columns

process(8)

part of result

columns: []
columns: [0]
columns: [0, 2]
columns: [0, 2, 4]
columns: [0, 2, 4, 1]
columns: [0, 2, 4, 1, 3]
columns: [0, 2, 4, 1]
columns: [0, 2, 4, 1, 7]
columns: [0, 2, 4, 1]
Sign up to request clarification or add additional context in comments.

2 Comments

You just want to debug your recursive function? Then I'd recommend using a debugger, not doing print-debugging. It may be sufficient for now, but please get used to debugging. If pdb is too cryptic for your taste, try Winpdb. It has a nice GUI and many nice features.
No i wanted to pass these changing list to another function inorder to simulate some movement
1

If I understood you correctly, you just want to pass a list of basic python types to another Python process which you want to call from here. You could just use any way of serialization and deserialization.

An easy one would be (if your list really just contains basic types like int, float, string, ...) to use JSON

import json
import subprocess

list_to_transfer = [1,2,"sdf",5.6]
list_as_string = json.dumps(list_to_transfer)

subprocess.call("other_executable \"%s\"" % list_as_string, shell=True)

In the other process, just deserialize by doin

import json
import sys

list_from_other_process = json.loads(sys.argv[1])

I didn't try that code, maybe it doesn't run, but the main idea should be clear.

Comments

1

If you have two files in the same directory you can do this:

  • file1.py

    def function1(list):
        print(list)
    
  • file2.py

    import file1
    file1.function1(['hallo'])
    

You can use import for this.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.