function changing input value
The following code is supposed to implement a basic percolation process on a matrix of 0's and 1's. For some reason, it's changing the value of the matrix I input, and I can't figure out why. I'm sure it's a basic error on my part, but if someone can set me straight, I'd appreciate it!
Here's the function I defined:
n = 4;
def percolate(B):
update = B;
for i in [0..n-1]:
for j in [0..n-1]:
nbr_sum = 0;
if (i==0):
nbr_sum += B[i+1,j];
elif (i==n-1):
nbr_sum += B[i-1,j];
else:
nbr_sum += B[i-1,j]+B[i+1,j];
if (j==0):
nbr_sum += B[i,j+1];
elif (j==n-1):
nbr_sum += B[i,j-1];
else:
nbr_sum += B[i,j-1]+B[i,j+1];
if (nbr_sum > 1):
update[i,j] = 1;
return update;
When I execute
Bid = matrix.identity(n);
percolate(Bid)
I get the expected output
[1 1 0 0]
[1 1 1 0]
[0 1 1 1]
[0 0 1 1]
but the value of Bid
also changes to the same value (as opposed to continuing to be the n x n identity matrix, as desired).
Use
update = B.copy()
, otherwiseupdate
is the same asB
. By the way, no need for all these;