How to Think Like a Computer Scientist: Learning with Python 2nd Edition/Solutions/CH 9

From Wikibooks, open books for an open world
Jump to navigation Jump to search

Chapter 9[edit | edit source]

CH 9 - Solution 1[edit | edit source]

x = ['spam!', 1, ['Brie', 'Roquefort', 'Pol le Veq'], [1, 2, 3]]

for i in x:
    print len(i)


>>> 
5
Traceback (most recent call last):
  File "C:\Python26\ch9.py", line 5, in <module>
    print len(i)
TypeError: object of type 'int' has no len()
>>>


x = ['spam!', 'one', ['Brie', 'Roquefort', 'Pol le Veq'], [1, 2, 3]]

for i in x:
    print len(i)


>>> 
5
3
3
3
>>>

CH 9 - Solution 2[edit | edit source]

CH 9 - Solution 2.1[edit | edit source]

"""
  >>> a_list[3]
  42
  >>> a_list[6]
  'Ni!'
  >>> len(a_list)
  8
"""


a_list = [1, 2, 3, 42, 5, 6, 'Ni!', 8]


if __name__ == '__main__':
    import doctest
    doctest.testmod()

CH 9 - Solution 2.2[edit | edit source]

"""
  >>> b_list[1:]
  ['Stills', 'Nash']
  >>> group = b_list + c_list
  >>> group[-1]
  'Young'
"""

b_list = ['Crosby', 'Stills', 'Nash'] 
c_list = ['Young']

if __name__ == '__main__':
    import doctest
    doctest.testmod()

CH 9 - Solution 2.3[edit | edit source]

"""
  >>> 'war' in mystery_list
  False
  >>> 'peace' in mystery_list
  True
  >>> 'justice' in mystery_list
  True
  >>> 'oppression' in mystery_list
  False
  >>> 'equality' in mystery_list
  True
"""

mystery_list = ['peace', 'justice', 'equality']


if __name__ == '__main__':
    import doctest
    doctest.testmod()

CH 9 - Solution 2.4[edit | edit source]

"""
  >>> range(a, b, c)
  [5, 9, 13, 17]
"""

a = 5
b = 18
c = 4


if __name__ == '__main__':
    import doctest
    doctest.testmod()

CH 9 - Solution 3[edit | edit source]

>>> range(10, 0, -2)
[10, 8, 6, 4, 2]

What happens if start is less than stop and step is less than 0?

The result will be an empty list.

Write a rule for the relationships among start, stop, and step.

CH 9 - Solution 4[edit | edit source]

>>> a = [1, 2, 3]
>>> b = a[:]
>>> id(a)
18484400
>>> id(b)
18594872
>>> b[0]
1
>>> b[0] = 5
>>> id(a)
18484400
>>> id(b)
18594872
>>> b
[5, 2, 3]
>>> a
[1, 2, 3]

CH 9 - Solution 5[edit | edit source]

>>> this = ['I', 'am', 'not', 'a', 'crook']
>>> that = ['I', 'am', 'not', 'a', 'crook']
>>> print "Test 1: %s" % (id(this) == id(that))
Test 1: False
>>> that = this
>>> print "Test 2: %s" % (id(this) == id(that))
Test 2: True
>>>

CH 9 - Solution 6[edit | edit source]

CH 9 - Solution 6.1[edit | edit source]

"""
  >>> 13 in junk
  True
  >>> del junk[4]
  >>> junk
  [3, 7, 9, 10, 17, 21, 24, 27]
  >>> del junk[a:b]
  >>> junk
  [3, 7, 27]
"""

junk = [3, 7, 9, 10, 13, 17, 21, 24, 27]
a = 2
b = (len(junk) - 2)

if __name__ == '__main__':
    import doctest
    doctest.testmod()

CH 9 - Solution 6.2[edit | edit source]

"""
  >>> nlist[2][1]
  0
  >>> nlist[0][2]
  17
  >>> nlist[1][1]
  5
"""

nlist = [[1, 2, 17], [4, 5, 6], [7, 0, 9]]

if __name__ == '__main__':
    import doctest
    doctest.testmod()

CH 9 - Solution 6.3[edit | edit source]

"""
  >>> import string
  >>> string.split(message, '??')
  ['this', 'and', 'that']
"""

message = "this??and??that"

if __name__ == '__main__':
    import doctest
    doctest.testmod()

CH 9 - Solution 7[edit | edit source]

def add_vectors(u, v):
    """
      >>> add_vectors([1, 0], [1, 1])
      [2, 1]
      >>> add_vectors([1, 2], [1, 4])
      [2, 6]
      >>> add_vectors([1, 2, 1], [1, 4, 3])
      [2, 6, 4]
      >>> add_vectors([11, 0, -4, 5], [2, -4, 17, 0])
      [13, -4, 13, 5]
    """
    
    new_list = []
    for index, value in enumerate(u):
        for index2, value2 in enumerate(v):
            if index == index2:
                new_list += [value + value2]
    return new_list

    #However, a less complex solution follows:
    new_list = []
    for index, value in enumerate(u):
        new_list += [u[index] + z[index]]
    return new_list

if __name__ == '__main__':
    import doctest
    doctest.testmod()

CH 9 - Solution 8[edit | edit source]

def mult_lists(a, b):
    """
      >>> mult_lists([1, 1], [1, 1])
      2
      >>> mult_lists([1, 2], [1, 4])
      9
      >>> mult_lists([1, 2, 1], [1, 4, 3])
      12
    """
    sm = 0
    new_list = []
    for x, elmt1 in enumerate(a):
        for y, elmt2 in enumerate(b):
            if x == y:
                new_list += [elmt1 * elmt2]
    q = len(new_list) - 1
    while q != -1:
        sm += new_list[q]
        q += -1
    return sm

if __name__ == '__main__':
    import doctest
    doctest.testmod()
#Simpler Code
#new_list = []
#for index, value in enumerate(b):
#new_list += [a*value]
#return new_list

CH 9 - Solution 9[edit | edit source]

CH 9 - Solution 9.1[edit | edit source]

def add_row(matrix):
    """
      >>> m = [[0, 0], [0, 0]]
      >>> add_row(m)
      [[0, 0], [0, 0], [0, 0]]
      >>> n = [[3, 2, 5], [1, 4, 7]]
      >>> add_row(n)
      [[3, 2, 5], [1, 4, 7], [0, 0, 0]]
      >>> n
      [[3, 2, 5], [1, 4, 7]]
    """
    y = len(matrix[0])

    matrix2 = matrix[:]
    for z in range(1):
        matrix2 += [[0] * y]
    return matrix2

if __name__ == '__main__':
    import doctest
    doctest.testmod()

CH 9 - Solution 9.2[edit | edit source]

def add_column(matrix):
    """
      >>> m = [[0, 0], [0, 0]]
      >>> add_column(m)
      [[0, 0, 0], [0, 0, 0]]
      >>> n = [[3, 2], [5, 1], [4, 7]]
      >>> add_column(n)
      [[3, 2, 0], [5, 1, 0], [4, 7, 0]]
      >>> n
      [[3, 2], [5, 1], [4, 7]]
    """
    x = len(matrix)

    matrix2 = [d[:] for d in matrix]
    for z in range(x):
        matrix2[z] += [0]
    return matrix2
      
if __name__ == '__main__':
    import doctest
    doctest.testmod()

CH 9 - Solution 10[edit | edit source]

def add_matrices(m1, m2):
    """
      >>> a = [[1, 2], [3, 4]]
      >>> b = [[2, 2], [2, 2]]
      >>> add_matrices(a, b)
      [[3, 4], [5, 6]]
      >>> c = [[8, 2], [3, 4], [5, 7]]
      >>> d = [[3, 2], [9, 2], [10, 12]]
      >>> add_matrices(c, d)
      [[11, 4], [12, 6], [15, 19]]
      >>> c
      [[8, 2], [3, 4], [5, 7]]
      >>> d
      [[3, 2], [9, 2], [10, 12]]
   """

    new_matrix = []
    for i, row in enumerate(m1):
        new_row = []        
        for j, m1_value in enumerate(row):
            m2_value = m2[i][j]
            new_row += [m1_value + m2[i][j]]
        new_matrix += [new_row]
    return new_matrix
      
if __name__ == '__main__':
    import doctest
    doctest.testmod()

CH 9 - Solution 11[edit | edit source]

def scalar_mult(n, m):
    """
      >>> a = [[1, 2], [3, 4]]
      >>> scalar_mult(3, a)
      [[3, 6], [9, 12]]
      >>> b = [[3, 5, 7], [1, 1, 1], [0, 2, 0], [2, 2, 3]]
      >>> scalar_mult(10, b)
      [[30, 50, 70], [10, 10, 10], [0, 20, 0], [20, 20, 30]]
      >>> b
      [[3, 5, 7], [1, 1, 1], [0, 2, 0], [2, 2, 3]]
    """

    new_matrix = []
    for row in m:
        new_row = []        
        for value in row:
            new_row += [value*n]
        new_matrix += [new_row]
    return new_matrix    

    
if __name__ == '__main__':
    import doctest
    doctest.testmod()

CH 9 - Solution 12[edit | edit source]

# Once we have obtained lists for the relevant rows and columns
# in row_times_column function, we will re-use the mult_lists
# function from question 8:

def mult_lists(a, b):
    sum = 0
    for i, a_value in enumerate(a):
        sum += a_value * b[i]
    return sum


def row_times_column(m1, row, m2, column):
    """
      >>> row_times_column([[1, 2], [3, 4]], 0, [[5, 6], [7, 8]], 0)
      19
      >>> row_times_column([[1, 2], [3, 4]], 0, [[5, 6], [7, 8]], 1)
      22
      >>> row_times_column([[1, 2], [3, 4]], 1, [[5, 6], [7, 8]], 0)
      43
      >>> row_times_column([[1, 2], [3, 4]], 1, [[5, 6], [7, 8]], 1)
      50
    """
    m1_row = m1[row]
    m2_col = []
    for m2_row in m2:
        m2_col += [m2_row[column]]
    return mult_lists(m1_row, m2_col)

#This code may also be used to bypass the mult_lists code

def row_times_column(m1, row, m2, column):
	x = 0
	y = 0
	for a in m1[row]:
		t = a * m2[x][column]
		y += t
		x += 1
	return y

def matrix_mult(m1, m2):
   """
      >>> matrix_mult([[1, 2], [3,  4]], [[5, 6], [7, 8]])
      [[19, 22], [43, 50]]
      >>> matrix_mult([[1, 2, 3], [4,  5, 6]], [[7, 8], [9, 1], [2, 3]])
      [[31, 19], [85, 55]]
      >>> matrix_mult([[7, 8], [9, 1], [2, 3]], [[1, 2, 3], [4, 5, 6]])
      [[39, 54, 69], [13, 23, 33], [14, 19, 24]]
    """

#To pass these tests, the function needs to multiply each each m1 row
#by each m2 column, to produce a new matrix with with the same number
#of rows as m1, and the same number of columns as m2. (This is the way
#matrices are commonly multiplied in mathematics). We can use
#row_times_column for each row/column combination

   m1_num_rows = len(m1)
   m2_num_cols = len(m2[0])
   product_matrix = []
   for row in range(m1_num_rows): 
       new_row = []
       for column in range(m2_num_cols):
           new_row += [row_times_column(m1, row, m2, column)]
       product_matrix += [new_row]
   return product_matrix


if __name__ == '__main__':
    import doctest
    doctest.testmod()

CH 9 - Solution 13[edit | edit source]

CH 9 - Solution 14[edit | edit source]

import string

def replace(s, old, new):
    """
      >>> replace('Mississippi', 'i', 'I')
      'MIssIssIppI'
      >>> s = 'I love spom!  Spom is my favorite food.  Spom, spom, spom, yum!'
      >>> replace(s, 'om', 'am')
      'I love spam!  Spam is my favorite food.  Spam, spam, spam, yum!'
      >>> replace(s, 'o', 'a')
      'I lave spam!  Spam is my favarite faad.  Spam, spam, spam, yum!'
    """
    s_without_old = string.split(s, old)
    s_with_new = string.join(s_without_old, new)
    return s_with_new

    
if __name__ == '__main__':
    import doctest
    doctest.testmod()

You can also do:

def myreplace(s, old, new):
    """
      >>> myreplace('Mississippi', 'i', 'I')
      'MIssIssIppI'
      >>> s = 'I love spom!  Spom is my favorite food.  Spom, spom, spom, yum!'
      >>> myreplace(s, 'om', 'am')
      'I love spam!  Spam is my favorite food.  Spam, spam, spam, yum!'
      >>> myreplace(s, 'o', 'a')
      'I lave spam!  Spam is my favarite faad.  Spam, spam, spam, yum!'
    """
    new_string = ""
    counter = 0
    while counter<len(s): 
        
        # check if old equals a slice of len(old)

        if old == s[counter:counter+len(old)]:
            new_string += new #s[counter+len(old):]
            counter+=len(old)
        else:
            new_string += s[counter]
            counter += 1
    return new_string

 if __name__ == '__main__':
    import doctest
    doctest.testmod(verbose=True)