First Summer 2006


Lab Fifteen: Mock Practical.
Let's work out problem 16 in Lecture Notes Eighteen, and not necessarily using objects:

def row_sums(matr):
    result = []
    for row in matr:
        result.append(sum(row))
    return result

m = [[1,2], [4,5]]
print row_sums(m) # prints [3, 9]

Turns out there is a sum method already.

In any event we can write that ourselves, if need be.

For the next problem index availability becomes paramount:

def col_sums(matr):
    sums = [0] * len(matr[0])
    for i in range(len(matr)):
        for j in range(len(matr[i])):
            sums[j] += matr[i][j]
    return sums

m = [[1, 2, 3], [4, 1, 2]]
print col_sums(m)

You also notice the shortcut for creating an initial list of a given length.

Next, the transpose method:

def transpose(matrix):
    width = len(matrix[0])
    height = len(matrix)
    result = []
    for i in range(width):
        result.append([0]*height)
    for i in range(width):
        for j in range(height):
            result[i][j] = matrix[j][i]
    return result

m = [[1, 2, 3], [4, 1, 2]]
print transpose(m)

Finally, let's work on the last problem:

def matrix_string(matrix):
    result = ""
    for row in matrix:
        for elem in row:
            result += str(elem).rjust(3)
        result += "\n"
    return result

m = [[1, 2, 3], [4, 1, 2]]
print matrix_string(m)

With this we can retry some of the programs before:

def matrix_string(matrix):
    result = ""
    for row in matrix:
        for elem in row:
            result += str(elem).rjust(3)
        result += "\n"
    return result

def transpose(matrix):
    width = len(matrix[0])
    height = len(matrix)
    result = []
    for i in range(width):
        result.append([0]*height)
    for i in range(width):
        for j in range(height):
            result[i][j] = matrix[j][i]
    return result

m = [[1, 2, 3], [4, 1, 2]]
print matrix_string(m)
print matrix_string(transpose(m))

Now Homework Eight should present little problems.


Last updated: June 6, 2006 by Adrian German for A201/A597