-2

I am currently trying a mathematics and computing course and hit a snag. The question I have been asked to produce a program for is:

Write a program to store the contents of a 6 by 6 matrix. The matrix M has been defined such that the value of the ith and jth column of the matrix is the result of multiplying i and j.

The JavaScript code is below:

var m = new Array();
var i,j;

for (i=0;i<6;i++){
    m[i]=new Array(6);
    for (j=0;j<6;j++){
        m[i][j]=(i+1)*(j+1);
    }
}
print m

My question is what would the same code look like in Python. I have tried the program below but hit with type and assignment errors.

m=[]
i=0
j=0

for i in xrange (6):
    m.append(i)
for j in xrange (6):
    m[i][j]=((i+1)*(j+1))

print m

Any help would be greatly appreciated.

doniyor
  • 31,751
  • 50
  • 146
  • 233
Gallieon474
  • 55
  • 1
  • 7

1 Answers1

2

In the first loop, in the line m.append(i), you are appending the index number to m. After the loop m will be [0, 1, 2, 3, 4, 5]. You want to assign a list:

for i in xrange(6):
    m.append([0] * 6)   # [0]*6 == [0, 0, 0, 0, 0, 0]

Also your indentation is off. The second loop is part of the first loop:

m = [] # no need to initialize i and j
for i in xrange(6):
    m.append([0] * 6)
    for j in xrange(6):
        m[i][j] = (i+1) * (j+1)
print m
[[1, 2, 3, 4, 5, 6],
 [2, 4, 6, 8, 10, 12],
 [3, 6, 9, 12, 15, 18],
 [4, 8, 12, 16, 20, 24],
 [5, 10, 15, 20, 25, 30],
 [6, 12, 18, 24, 30, 36]]
kay
  • 23,543
  • 10
  • 89
  • 128
  • Thanks so much. This was exactly what I was looking for. So I take it that the new append statement creates the 6 rows of the matrix. Thank you! – Gallieon474 Aug 06 '14 at 21:40
  • Also why don't you need to initialise i and j - is it because they are being used as counters? Sorry for the influx of questions, just eager to learn – Gallieon474 Aug 06 '14 at 21:51
  • "just eager to learn", that's what SO is there for :-D. Variables in Python are either global (file scoped) or local (function scoped). There is no such thing like "for loop scoped", which C-like languages use. In Python, if you write anywhere to the variable, then it is part of this scope. You just must not read it before you write to it. In the for-loop you write the variables, and you don't use them readingly before. – kay Aug 07 '14 at 03:23
  • Thanks for that. Finally, what is the difference between using xrange (6) and range (0,6,1) – Gallieon474 Aug 07 '14 at 08:48
  • (In Python2) `range` creates a new list, `xrange` creates a [generator](http://stackoverflow.com/q/1756096/). If your range is not very big, then (in Python2) `range` is much faster than `xrange`. Both functions take the same arguments: `range(LIMIT) == range(0, LIMIT) == range(0, LIMIT, 1)`, first you can omit the start, also you can omit the step size. – kay Aug 07 '14 at 16:22