How to pass python list dynamically to another pyt

2019-09-07 02:19发布

问题:

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

回答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]


回答2:

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.



回答3:

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.