1
对于人工智能assingment我试图通过将数组作为返回值发送到生成函数来获得4个单独的数组。发送数组1时,它正常工作。但是当发送数组2,3和4时,它将覆盖先前生成的数组。在最后阵列的输出,array4是在这一刻:从函数返回时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()
python通过引用的方式工作,所以很可能(因为您的代码有点不清楚)您正在重新使用引用。尝试传递一个矩阵的副本到gen_matrix,然后每个都应该独立更新。 https://docs.python.org/2/library/copy.html –
请修复您的缩进。 –