15-112 Spring 2013 Practice Quiz 2

* No calculators, no notes, no books, no computers.
SHOW YOUR WORK, CIRCLE YOUR ANSWERS.

  1. Quick Answers.

    1. Give at least 4 different ways to print the even numbers from 200 to 1000, inclusive.

    2. Show how to rewrite an arbitrary "for" loop that uses an xrange so that it uses a "while" loop instead.

    3. Explain the difference between range and xrange (in Python 2.7).  Give an example where one would work and the other would crash.
       

  2. Code Tracing

    Indicate what each will print:

    def f(x,y):
        for z in xrange(x,y):
            if (z%x == 0):
                print z,
            elif (z < (x+y)/2):
                print ".",
            if (z%5 == 1):
                print "*",
    f(2, 16)
    
    def g(z):
        for x in xrange(0,z,4):
           print "#", x, ":",
           for y in xrange(x, 0, -3):
               print (x,y),
           print
    
    g(15)
  3. Reasoning Over Code

    Find arguments for the following functions that make them return True.

    def f(x,y,z):
        assert(type(x) == type(y) == type(z) == int)
        assert(100 > x > y > z > 0)
        s = t = 0
        for q in xrange(y,x,z): # note the order, y before x
            s += 1
            t += q
        return ((s == 3) and (t == 99) and
                (x/10 == y/10) and (x%10 == t%10))
    
    def g(z):
        assert((type(z) == int) and (100>z>0))
        s = y = 0
        while (s < z):
            y += 1
            s = 0
            for m in xrange(y):
                for n in xrange(y):
                    s += 1
        return ((y == 5) and (s%z == y))
  4. Free Response

    Here you would be expected to write any of the functions from hw2, or from practice-thru-week2, or any variant of those, or anything similarly challenging.  For example:

    longestDigitRun(x)
    Write a function that takes an int value n and returns the length of the longest run of the consecutive matching digits.  For example, longestDigitRun(11777332) returns 3 because there is a run of 3 consecutive 7's.