CS30 - Spring 2015 - Class 18
Example code in this lecture
matrix.py
tic_tac_toe.py
Lecture notes
Admin
- Assignment 8 out and due Sunday at 11:59pm
- office hours this week
- Tuesday 7-8pm (instead of 7-9pm)
- Thursday 7-8pm (instead of 7-9pm)
- Saturday 1-3pm
representing matrices in python
- what is a matrix?
- a two-dimensional structure, e.g.
0 1 0
1 8 2
5 0 3
- it has rows and columns
- the 2nd row is:
1 8 2
- the second column is:
1
8
0
- for computer science, we'll start indexing at 0, for the first row is row 0 and the first column, is column 0
- indexing into matrices
- individual entries in a matrix can be talked about by specifying a row and a column
- say the matrix above is called m, what entry does m[1][2] represent?
- in math, we might write this m(1, 2)
- 1 = second row, 2 = third column: 2
- how would get get at the 3 in the above matrix?
- m[2][2]
- how can we do this in python?
- list of lists!
>>> m = [[0, 1, 0], [1, 8, 2], [5, 0, 3]]
>>> m
[[0, 1, 0], [1, 8, 2], [5, 0, 3]]
>>> m[1][2]
2
>>> m[2][2]
3
- could have also constructed this as:
>>> m = []
>>> m.append([0,1,0])
>>> m.append([1, 8, 2])
>>> m.append([5, 0, 3])
>>> m
[[0, 1, 0], [1, 8, 2], [5, 0, 3]]
>>> m[1][2]
2
>>> m[2][2]
3
- what does m[1] represent?
- the second row!
>>> m[1]
[1, 8, 2]
- matrices are just a list of lists
look at
matrix.py code
- what does zero_matrix and zero_matrix2 do?
- creates a size by size matrix with all entries zero
- zero_matrix does this an entry at a time
- zero_matrix2 does this a row at a time
>>> zero_matrix(3)
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>> zero_matrix(2)
[[0, 0], [0, 0]]
>>> zero_matrix(1)
[[0]]
>>> m = zero_matrix(2)
>>> m[1][1] = 100
>>> m
[[0, 0], [0, 100]]
- what does random_matrix do?
- same thing, but puts random numbers in
>>> random_matrix(3)
[[7, 9, 9], [3, 6, 6], [6, 6, 2]]
>>> random_matrix(3)
[[9, 5, 8], [1, 2, 3], [8, 9, 8]]
>>> random_matrix(3)
[[1, 0, 0], [4, 3, 8], [2, 7, 7]]
- how would we print out a matrix in a more normal form (a row at a time)?
- iterate for the rows and print each out
- look at print_matrix function in
matrix.py code
- what does the identity function do in
matrix.py code
?
- creates an identity matrix, all zeros except for ones along the diagonal
- how would we sum up all the numbers in a matrix?
- iterate over each entry and add them up
- look at matrix_sum function in
matrix.py code
- what does len(m[row]) give us?
- the number of columns (in that row, technically)
look at
tic_tac_toe.py code
- how would you represent a tic tac toe board?
- a 3 by 3 matrix
- each entry has one of three values:
- empty
- X
- O