15-112 Spring 2013 Quiz 2

* 20 Minutes.  No calculators, no notes, no books, no computers. 
* Show your work. Circle your answers.

1.    Quick Answers. [20 pts]

a.    What does the "pass" statement do?

b.    Rewrite the following so that it uses a conditional instead of boolean arithmetic:
y = ((x > 0) * 99)

c.    Rewrite the following so that it uses a "while" loop instead of a "for" loop:
for x in xrange(10, 135, 2):
    print x

d.    Give an example where "xrange" would work but "range" would crash (in Python 2.7).
 

2.    Code Tracing [20 pts]  Indicate what each will print:

def f(x,y):

    m = 0

    for z in xrange(x,y,2):

        if (z%x == m):

            print z,

            m += 1

        elif (z%x == m+3):

            print ".",

        if (z%5 == 1):

            print "*",

f(5, 12)

 

 

def g(z):

    for x in xrange(1,z,3):

       print "#", x, ":",

       for y in xrange(z, x, -2):

           print (x,y),

       print

g(6)

3.    Reasoning Over Code [20 pts]
Find arguments for the following functions that make them return True.

def g(z):
    assert((type(z) == int) and (100>z>0))
    for x in xrange(z):
        s = 0
        for y in xrange(6, 5*x, 4):
            s += y
    return (s == 48)


def f(x,y):

    assert(type(x) == type(y) == int)

    assert(100 > x > y > 0)

    s = 0

    if (x == 4*y):

        while (x > y):

            y += 1

            x -= 2

            s += 1

    return (s == 20)

4.    Free Response: moreOddThanEvenDigits [40 pts]
Write the function moreOddThanEvenDigits(n), which you may abbreviate as m(n), which takes a possibly-negative int value n and returns True if n contains more odd digits than even digits, ignoring leading 0's, and False otherwise.  So, m(-2325) returns False because -2325 contains two even digits (both 2's) and two odd digits (the 3 and the 5).
 

5.    Bonus/Optional: [5 pts]
[Hard] Find arguments for the following function that make it return True.
def f(z):
  assert(2000 >= z >= 0)
  s = x = 0
  while (s < 1050):
      y = 0
      for y in range(x): y += y*y**y
      q = y
      while (q > 10): q = q/10 + q%10
      s += y + q
      x += 1
  return (s == z)