2017-10-07 5 views
1

人工知能のアサーション私は、返り値として生成関数に配列を送ることによって4つの別々の配列を取得しようとしています。配列1を送るとき、それは正常に動作します。しかし、配列2,3、および4を送信すると、前に生成された配列を上書きします。関数から返されるPython上書き配列

['#', '#', '#', '#', '#'] 
['#', 'G', '☐', 'G', '#'] 
['#', '☐', 'P', '•', '#'] 
['#', 'P', '•', 'P', '#'] 
['#', '#', '#', '#', '#'] 

array4のための理想的な出力は次のとおりです:

以下
['#', '#', '#', '#', '#'] 
['#', 'G', '•', 'G', '#'] 
['#', '☐', '☐', '•', '#'] 
['#', 'P', '•', '•', '#'] 
['#', '#', '#', '#', '#'] 

である私の完全なPythonのコード:

def solver(): 
matrix = [['#', '#', '#', '#', '#'], ['#', 'G', '•', 'G', '#'], ['#', '☐', '☐', '•', '#', ], 
     ['#', '•', 'P', '•', '#'], ['#', '#', '#', '#', '#']] 
countx = 0 
county = 0 
cordp = [] 
for x in matrix: 
    county += 1 
    for y in x: 
     countx += 1 
     if y == 'P': 
      cordp = [countx, county] 
    countx = 0 
    print(x) 
# nieuwe stap 
    # wat is huidige positie 
cordp[0], cordp[1] = cordp[1]-1, cordp[0]-1 

n = gen_matrix(matrix, cordp, 0,-1) 
e = gen_matrix(matrix, cordp, 1,0) 
s = gen_matrix(matrix, cordp, 0,1) 
w = gen_matrix(matrix, cordp, -1,0) 

for x in n: 
    print(x) 

def gen_matrix(matrixnew, cordp, x, y): 
print (x) 
print(y) 
if matrixnew[cordp[0]+y][cordp[1]+x] == '☐': 
    if matrixnew[cordp[0]+y*2][cordp[1]+x*2] == '#': 
     print("ik kan doos niet verplaatsen") 
    else: 
     print("IK HEB EEN BOX en kan deze verplaatsen") 
     matrixnew[cordp[0]+y*2][cordp[1]+x*2] = '☐' 
     matrixnew[cordp[0]+y][cordp[1]+x] = 'P' 
     matrixnew[cordp[0]][cordp[1]] = '•' 
elif matrixnew[cordp[0]+y][cordp[1]+x] == '•': 
    print("ik heb een bolletje") 
    matrixnew[cordp[0]+y][cordp[1]+x] = 'P' 
    matrixnew[cordp[0]][cordp[1]] = '•' 
elif matrixnew[cordp[0]+y][cordp[1]+x] == '#': 
    print("ik heb een muur") 

return matrixnew 
solver() 
+3

Pythonは参照によって動作しますので、参照が再利用されている可能性があります(コードが多少不明なため)。代わりに行列のコピーをgen_matrixに渡してみて、それぞれを個別に更新する必要があります。 https://docs.python.org/2/library/copy.html –

+1

インデントを修正してください。 –

答えて

0

として最後の配列のための出力は、array4はこの時点でありますポールはコメントの中で、Pythonは値ではなく参照によってリストを渡すので、あなたの行列を上書きしていると指摘しました。

修正する前に、行列をコピーしてから修正してください。私たちは与えるために、この

n = gen_matrix([list(row) for row in matrix], cordp, 0,-1) 
e = gen_matrix([list(row) for row in matrix], cordp, 1,0) 
s = gen_matrix([list(row) for row in matrix], cordp, 0,1) 
w = gen_matrix([list(row) for row in matrix], cordp, -1,0) 

この

n = gen_matrix(matrix, cordp, 0,-1) 
e = gen_matrix(matrix, cordp, 1,0) 
s = gen_matrix(matrix, cordp, 0,1) 
w = gen_matrix(matrix, cordp, -1,0) 

を置き換えることができます

matrix_copy = [list(row) for row in original_matrix] 

私たちは、このように、つまりリストのリスト、2Dマトリックスをコピーすることができますgen_matrix各実行のためのマトリックスの新しいコピー。

関連する問題