Title: Mutating Row in a matrix
It will be obvious that I am a newbie here when you see my question, but here goes. I am writing my first program, and have encountered a problem which I’ve been able to reproduce in the short program below. Basically, I select a row (B) from a matrix and I want to keep B constant. Then I create a new matrix by copying the old, and mutate the new matrix. I then want to substitute the unmutated row B  into the mutated new matrix.

Problem: B changes, as you can see when you run the short program below. So does the original matrix, although I don’t care about that.

Question: Why does the list B change when I don’t work on it? I want to understand this.

Question #2: A solution would be to convert the list B into a tuple and then reconvert the tuple back into a list after the new matrix has been mutated and insert it, but I still want to understand why a list would change when I’m haven’t done anything to it.

Here’s a small program that reproduces the problem. When B changes depends upon the value you set for ‘e’

import random
A = [[1,1,1,1,1], [2,2,2,2,2],[3,3,3,3,3],[4,4,4,4,4]]
e = 2
B = A[e]
Columns = 4
Rows = 4
NewMatrix = A
MutationRate = .9999            #Mutation of NewMatrix
s = 0
while s<Rows:
    print "B is", B
    h=0
    while h<Columns:        #mutate individual members
        x=random.random()
        if x<=MutationRate:
            NewMatrix[s][h] = abs(NewMatrix[s][h] - 9)
        if h == Columns - 1: break
        h += 1
    if s ==Rows -1: break
    s += 1
print 'B is', B
print A
print "*******"
_______________________________________________
Pythonmac-SIG maillist  -  Pythonmac-SIG@python.org
http://mail.python.org/mailman/listinfo/pythonmac-sig

Reply via email to