Re: Yet another "simple" headscratcher

2014-06-01 Thread wxjmfauth
>>> # from my lib
>>> def NewMat(nr, nc, val=0.0):
... val = float(val)
... return [[val] * nc for i in range(nr)]
... 
>>> import vmio6
>>> aa = NewMat(2, 3)
>>> vmio6.pr(aa)
(   0.0e+000  0.0e+000  0.0e+000 )
(   0.0e+000  0.0e+000  0.0e+000 )
>>> aa[0][0] = 3.1416
>>> vmio6.pr(aa)
(   3.14160e+000  0.0e+000  0.0e+000 )
(   0.0e+000  0.0e+000  0.0e+000 )
>>> aa[1][1] = 1.2345
>>> vmio6.pr(aa)
(   3.14160e+000  0.0e+000  0.0e+000 )
(   0.0e+000  1.23450e+000  0.0e+000 )
>>>

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


Re: Yet another "simple" headscratcher

2014-05-30 Thread Ian Kelly
On Fri, May 30, 2014 at 9:38 PM, Josh English
 wrote:
> I am trying to whip up a quick matrix class that can handle multiplication.
>
> Should be no problem, except when it fails.
>
> [SNIP]
>
> def zero_matrix(rows, cols):
> row = [0] * cols
> data = []
> for r in range(rows):
> data.append(row)

Each row of the matrix that you create here is the *same* list, not
different lists that happen to be equal.  So when you mutate one row,
you mutate all of them.  See:
https://docs.python.org/3/faq/programming.html#how-do-i-create-a-multidimensional-list
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Yet another "simple" headscratcher

2014-05-30 Thread Gary Herron

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


Re: Yet another "simple" headscratcher

2014-05-30 Thread Josh English
Mea culpa, gang.

I found it.

It had absolutely nothing to do with the multiplication.

It was in zero_matrix.

I feel like a fool.

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