Contents

  1. mystery.py
  2. twod_exercises.py

mystery.py 1/2

[
top][prev][next]
# Solve the mystery of what this code does
# by Sara Sprenkle

def main():
    matrix = createMatrix()
    print("Before:")
    print(matrix)
    mystery(matrix)
    print("After:")
    print(matrix)

def mystery(a):
    """ What does this do? -- write an appropriate
    doc string """
    for row in range( len(a) ):
        for col in range( len(a[0]) ):
            if row == col:
                a[row][col] = 42
            else:
                a[row][col] += 1

def createMatrix():
    """
    Creates and returns the 2d list for practicing this problem
    """
    a0 = list(range(1,5))
    a1 = list(range(5,9))
    a2 = list(range(9,13))
    a = []
    a.append(a0)
    a.append(a1)
    a.append(a2)
    return a

main()

twod_exercises.py 2/2

[
top][prev][next]
# Practice with creating 2D Lists
# Sara Sprenkle

import test

def main():
    #rows = int(input("How many rows? "))
    #columns = int(input("How many columns? "))

    rows = 3
    columns = 4

    print("\nCorrect Matrix Creation:")
    print('-'*30)
    matrix = create2DList(rows, columns)
    print(matrix)

    print("\nAssigning matrix[1][2]=3")
    matrix[1][2] = 3
    
    print("Result: ")
    print(matrix)

    print("\n" + "*"*55)
    print("Incorrect Matrix Creation:")
    print('-'*30)

    matrix = noCreate2DList(rows, columns)
    print(matrix)

    print("\nAssigning matrix[1][2]=3")
    matrix[1][2] = 3

    print("Result: ")
    print(matrix)


def create2DList(rows, cols):
    """Returns a two-dimensional list filled with 0s that is 'rows' tall and
    'cols' wide."""
    twodlist = []
    for rowPos in range(rows):
        # creates a new list
        row = []
        for colPos in range(cols):
            row.append(0)
        twodlist.append(row)
    return twodlist

def noCreate2DList(rows, cols):
    """Does not create a 2D list because each 'row' points to the same list in
    memory."""
    
    twodlist = []
    # creates one list
    onerow = []
    for colPos in range(cols):
        onerow.append(0)
    for rowPos in range(rows):
        twodlist.append(onerow)
        
    return twodlist

def testCreation():
    rows = 3
    cols = 4
    expected = [ [0]*cols, [0]*cols, [0]*cols ] 
    
    working = create2DList(rows, cols)
    # this should pass
    test.testEqual( working , expected)
    
    notworking = noCreate2DList(rows, cols)
    # this passes but it doesn't mean that the code worked
    # we're not testing if the lists are different memory
    test.testEqual( notworking, expected)
    
    # if we modify the lists created, we'll see the problem
    expected[1][2] = 3
    working[1][2] = 3
    notworking[1][2] = 3
    
    # this should pass
    test.testEqual( working , expected)
    # this should not
    test.testEqual( notworking, expected)
    
#testCreation()

main()

Generated by GNU Enscript 1.6.6.