15-112 Fall 2011 Quiz 2: Version A

* 15 Minutes.  No calculators, no notes, no books, no computers.

1.       [60 pts] Do this first!
On the back of this sheet, write the function hasNines, that takes a value of unspecified type and returns True if it is a (possibly-negative) integer that contains at least one 9, and False otherwise.   For example, hasNines(8291) and hasNines(-8291) both return True, but hasNines(821), hasNines(29.2), and hasNines(False) all return False.
 

2.       [40 pts; 10 pts each]
Give values of x and y so that each code example prints True (without crashing).   Circle your answers.

a.  k = 0
for z in xrange(x,y,2):  # note the 2 in the xrange!
    k += 1
print (k == 3)
 

b.  k = 0
for z in xrange(4,7):
    k += (x^y) # note the bitwise operator!
print ((x > y > 0) and (k == 15))
 

c.  k = 0
while (x >= y):
    if (x % 2 == 0):
        k += (y % 3)
    x -= 1
print ((y > 0) and (k == 4))
 

d.      k = 0
for i in xrange(x):
    for j in xrange(i):  # note this uses i, not y!
        k += y
print ((y < 10) and (k == 42))

 

3.  Bonus/Optional [3 pts]:  State in a few words of plain English what this function does in general.
def f(x,y):
    assert(x > 0)
    while (x > 0):
        y -= x&1
        x >>= 1
    return (y == 0)


15-112 Fall 2011 Quiz 2: Version B

* 15 Minutes.  No calculators, no notes, no books, no computers.

1.       [60 pts] Do this first!
On the back of this sheet, write the function hasNines, that takes a value of unspecified type and returns True if it is a (possibly-negative) integer that contains at least one 9, and False otherwise.   For example, hasNines(8291) and hasNines(-8291) both return True, but hasNines(821), hasNines(29.2), and hasNines(False) all return False.
 

2.       [40 pts; 10 pts each]
Give values of x and y so that each code example prints True (without crashing).   Circle your answers.

a.  k = 0
for z in xrange(x,y,3):  # note the 3 in the xrange!
    k += 1
print (k == 3)
 

b.  k = 0
for z in xrange(3,7):
    k += (x^y)  # note the bitwise operator!
print ((x > y > 0) and (k == 24))
 

c.  k = 0
while (x >= y):
    if (x % 5 == 0):
        k += (y % 2)
    x -= 1

print ((y > 0) and (k == 3))
 

d.  k = 0
for i in xrange(y):
    for j in xrange(i):   # note this uses i, not y!
        k += x
print ((y < 10) and (k == 42))
 

3.       Bonus/Optional [3 pts]:  State in a few words of plain English what this function does in general.
def f(x,y):
    assert(x > 0)
    while (x > 0):
        y -= x&1
        x >>= 1
    return (y == 0)


carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem