CS 151: Homework

Homeworks

Current HW

HW Solutions

Homeworks are short assignments intende to reinforce concepts from lectures that are not necessarily covered in the weekly projects. The due dates are given along with the assignments. No credit will be given for late homework, as we will often be discussing the solutions in class.


HW 1: Assignments and Functions

Answer these questions on paper first and then check yourself using the Python interpreter. Correct your answer, if necessary, with a short explanation of why your first answer did not match the Python output, but don't erase your first answer. Hand in your written answers, with the corrections. You'll get full credit if you do all of the problems and the corrected versions of your answers are correct.
  1. Given the following Python expressions, write down the expected value of each.
    >>> 5 - 4 + 3
    >>> 5 - 4 * 3
    >>> 5 / 4 + 3
    >>> 5 / (4 + 3)
    >>> 5.0 / (4 + 3)
    
  2. Given the following Python code, write down what Python would print.
    >>> a = 4
    >>> b = 5
    >>> print a / b
    >>> print float(a) / b
    >>> print a * "blah "
    
  3. Given the following code, there is a single error on each line. Identify each error. If you fix all of the errors, what does it print out?
    >>> a = 3.0 * "blah "
    
    >>> b = "like to say " + A
    
    >>> c = 'you " + b
    
    >>> "I know " = d
    
    >>> pritn d + c
    
    
  4. Given the following Python code, what values are printed by the program?
    def afunc( B ):
        B = B * 2
        print B
    
    A = 3
    afunc( A )
    print A
    

HW 2: Functions, loops, and assignments

For each of the following problems, write down your answer after reading the problem. Then run the code in Python and double-check your answer. If your first answer was does not match, write down Python's answer and briefly explain why your answer did not match the Python output.

  1. Given the following Python code, write down what Python would print.
    a = 2
    b = 3
    for i in range(a):
        for j in range(b):
            print "very "*i + "yummy "*j
    
  2. Given the following Python code, write down what Python would print.
    def emphasize( phrase ):
        return 'wicked ' + phrase
    
    statement = 'cold'
    print emphasize( statement )
    print 'Maine gets ' + emphasize( emphasize( statement ) )
    
  3. Given the following Python code, write down what Python would print.
    expression = "ah "
    expression = "ah " + expression
    expression = "ah " + expression
    expression = "ah " + expression
    expression = expression + "choooo"
    print expression
    

HW 3: Lists

For each of the following problems, write down your answer after reading the problem. Then run the code in Python and double-check your answer. If your first answer was does not match, write down Python's answer and briefly explain why your answer did not match the Python output.

The first two problems are based on the following statements.

a = [1, 2, 3, 4]
b = [ ['a', 'b'], ['c', 'd'], 'what?' ]
c = [ 'four', 'score', 'and' ]
d = []

for i in range( len( a ) ):
    d.append( a[i] )
  1. What do each of the following print?
    • print a[2]
    • print b[1]
    • print b[1][1]
    • print c[2]
    • print d[10]
    • print b[2][4]
    • print a[-1]
  2. What does the following print?
    print a + c
    
  3. Write the symbol tables that describe the state of the computer at the first mark, then show what changes in the last statement.
    x = [1, 2]
    y = x
    z = [ x[0], y[0] ]
    # write down symbol tables here
    y[0] = 10
    # mark down what changes
    

HW 4: Loops and Lists

a = [ 1, 2, 3 ]
b = [ 4, 5, 6 ]
c = a + b
d = c[0:3]
e = d
a[0] = 10
c[-1] = 20
e[2] = 30
  1. For each of the following expressions, write down what Python would print after executing the code above.
    1. print a
    2. print b
    3. print c
    4. print d
    5. print e
    6. print c[2:4]
    7. print c[:-1]
  2. How many different list objects exist after executing the code above?
  3. Given the following code, what would Python print?
    people = [ 'Washington', 'Adams', 'Jefferson', 'Madison', 'Monroe' ]
    sentence = ''
    for name in people[:-1]:
        sentence = sentence + name + ', '
    sentence = sentence + ' and ' + people[-1]
    print sentence
    

HW 5: Objects

This homework is due on Monday, October 18, 2010

Download the linked file and graphics.py. Run the hw5.py program first. Then look at it and answer the following questions.

  1. How many graphics objects does the code create?
  2. How many graphics objects can the code access?
  3. How does the program figure out if the player has won the game?
  4. How does the program figure out if the player has lost the game?
  5. What does the expression word.find( guess ) return?

HW 6: Files and L-Systems

Due Friday, October 29, 2010

As with prior assignments, when possible, write out your answer and then check your answer by running the code.

  1. Consider the following L-system

    base: X
    X -> YF+F
    Y -> XF-F
    

    After one iteration of replacement, the base string becomes YF+F. Show the resulting string after three iterations.

    Once you've worked it through on your own, check your answer.

  2. Consider the following three lines of code.
    s = 'rule F F[+F][-F]'
    words = s.split()
    print words
    

    What does the print statement write?

  3. Given a file named sysA.txt with the contents
    base F--F--F
    rule F ff
    rule f F
    

    and the code

    fp = file( 'sysA.txt', 'r' )
    lines = fp.readlines()
    fp.close()
    
    for line in lines:
      words = line.split()
      for word in words:
        print word
    

    What would the program print to the terminal?


HW 7: Classes and Symbol Tables

Due Friday, November 5, 2010

Write down your answers to each question, then check your answer using Python. Write down any corrections and explain why you had to correct your answer.

Python gives you the ability to see all of the identifiers in a symbol table using the dir function. If you write print dir() in your code, it prints out a list of all of the symbols in the current symbol table at that point in the program's execution. If you give the function an argument, like dir(list), then it prints out the symbol table associated with the contents of the variable (a class, in the case of list).

Download and look at the student.py file from class. After you answer the questions, run the file and look at the result. Except for the __init__ and __str__ entries, ignore the symbols that start with __.

  1. Write down the global symbol table at the end of the file. There should be four items in it [Hint: remember loop variables].
  2. Write down the symbol table for the Student class. There should be nine items in it.
  3. Write down the symbol table for the __init__ function after executing the first three lines of code (# mark 1).
  4. Write down the symbol table for the first Student in the students list (Mary at # mark 2).
  5. When the code calls the sort method on the students list (# mark 3), it passes the expression Student.compare as the argument. What does the expression Student.compare mean? Explain it by referring to a symbol table.

HW 8: Dictionaries

Due Friday, November 12, 2010

Answer the questions below given the following Python code. Answer the questions without executing the code, then execute the code and correct and explain any differences.

a = {}
b = { 'hello' : 'world' }
c = dict()
d = dict( [ ['sunny', 'afternoon'], [ 'blustery', 'day' ] ] )
e = dict( b.items() + d.items() )
a[ 'cold' ] = 'winter'
a[ 'frozen' ] = 'trundra'
d[ 'cool' ] = 'breeze'
  1. What does each of the follow lines print?
    print a.keys()
    print b.keys()
    print c.keys()
    print d.keys()
    print e.keys()
    
  2. What does each of the following lines print?
    print a['cold']
    print d.get( 'sunny', 'morning' )
    print d.get( 'overcast', 'morning' )
    print c[ 'day' ]
    print e[ 'hello' ]
    
  3. Given the following class definition:
    class Agent:
      def __init__( self, things ):
        self.mystuff = dict( things )
    
    q = Agent( [ [ 'jacket', 'fleece' ], ['tshirt', 'cotton'], ['backpack', 'nylon'] ] )
    print q.mystuff.keys()
    
    1. Show the symbol table for the class Agent.
    2. Show the symbol table for the object referenced by q.
    3. Show the symbol table for the __init__ method.
    4. Show what the last line prints.

HW 9: Dictionaries and Recursion

Due Friday, November 19, 2010

Answer the questions below given the following Python code. Answer the questions without executing the code, then execute the code and correct and explain any differences.

def SumSquares( items ):
    if len(items) == 0:
        return 0
    else:
        return items[0]*items[0] + SumSquares( items[1:] )

def WinterAtColby( descriptor ):
    if len(descriptor) < 20:
        print descriptor
        WinterAtColby( 'wicked ' + descriptor )
        print descriptor
    else:
        print 'wicked ' + descriptor

home = {}
home[ 'Columbus Day' ] = 'huh?'
home[ 'Thanksgiving' ] = 'good food'
home[ 'Winter Break' ] = 'more good food'
home[ 'Spring Break' ] = 'good rest'
home[ 'Summer Break' ] = 'sunshine, beaches'
del home['Columbus Day']
home[ 'Summer Break' ] = 'get back to Colby'
  1. What does SumSquares( [1, 2, 3] ) return? Trace out the SumSquares symbol tables for the recursive execution of the function. In particular, show the value of items with each recursive call.
  2. What does WinterAtColby( 'cold' ) print?
  3. Show what each of the following prints after executing the code above.
    • print home.keys()
    • print home.get( 'Thanksgiving', 'more food' )
    • print home[ 'Columbus Day' ]
    • print home[ 'Summer Break' ]

HW 10: More Random Stuff

Due Friday, 3 December, 2010

Answer the questions below given the linked Python code. Answer the questions without executing the code, then execute the code and correct and explain any differences.

  1. In the subdivide function, how many line segments are in the return list compared to the input list?
  2. In the main function, in the loop over range(5), how many line segments are in the lines variable at the beginning of each loop?
  3. What are the entries and types in the symbol table for the main function at the raw_input line?
  4. What are the entries and types in the symbol table for the subdivide function at the return line?
  5. Will the bubbles function terminate? Why?
  6. If you called the bubbles function using bubbles(0, 0, 4), how many times would the bubbles function execute? How many bubbles would it draw? Are these different than the deepest level of recursion?

HW 11: Last Practice

Due Friday, 10 December, 2010

Answer the questions below given the linked Python code. Answer the questions without executing the code, then execute the code and correct and explain any differences.

  1. What does cbb contain at mark 1?
  2. What does cbb contain at mark 2?
  3. What does cbb contain at mark 3?
  4. What does the function print out at the end?