On 05/30/2014 08:38 PM, Josh English wrote:
...

def zero_matrix(rows, cols):
     row = [0] * cols
     data = []
     for r in range(rows):
         data.append(row)

     return Matrix(data)

There is a simple and common newbie mistake here. It looks like you are appending several copies of a zero row to data, but in fact you are appending multiple references to a single row. (The hint is that you only created *one* row.)

Put the
   row = [0] * cols
inside the loop so each append is using its own row rather than one shared row being used multiple times.


Here's a small example that demonstrates problem:

>>> row = [0,0,0,0]
>>> data = []
>>> data.append(row)
>>> data.append(row)
>>> data[0][0] = 99
>>> data
[[99, 0, 0, 0], [99, 0, 0, 0]]


Gary Herron



--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to