15-112 Spring 2013 Quiz 1

* 20 minutes.  No calculators, no notes, no books, no computers.
* No loops or conditionals or recursion!
SHOW YOUR WORK, CIRCLE YOUR ANSWERS.

1.      Quick Answers.  [20 pts]

a.       If x is a positive integer, what does (x % 1) equal?

b.      If x is a positive float, what does (x % 1) equal?

c.       What is the common term we use to describe integers x where (x % 2) equals 1?

d.      For an arbitrary float x, give a Python expression that represents the nearest int (not float) value to x.
 

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

def f(x):

    return x*2+x%2

 

def g(x):

    return x+3

 

def h(x,y):

    return g(f(y)) % f(g(x))  # note the order of x and y

 

print h(7,f(7))
 

############################################

 

def h():

    print 2+3*5, 2**3%5, (2/3 == 3/5)

    print 0 or 1 or 2 or "maybe" or "yes!" or True

h()

3.      Reasoning Over Code  [20 pts]
Find arguments for the following functions that make them return True.  You only need one set of arguments for each function, even if there are multiple correct answers.

def f(x,y):
    return ((type(x) == type(y) == int) and
            (100 > x > y > 0) and
            (x/10 == y%10 + 8) and
            (x/10 == x%10 + y) and
            (y/10 < y%10))

############################################

def g(x):
    assert((type(x) == int) and (100 > x > 0))
    a = x / 13
    b = x / 16
    c = x / 37
    return ((a > b) and (b <= c) and (x%7 == a+b+c))
 

4.      Free Response:  isPal  [40 pts]
Write the function isPal(x) that takes a possibly non-numeric value x and returns True if that value is a non-negative integer less than a thousand, and is also a palindrome (the same forwards as backwards).  Return False (without crashing) in all other cases.  Note that leading 0's are not a special case, so 50 is really 050, so isPal(50) returns True.
Note:  You may not use functions from the hw as helper functions unless you rewrite them here.

 

5.      Bonus/Optional  [1 pt each]

a.       Consider the following function where x and y are ints:
def f(x,y): return ((x > y) and x) or y
Assuming x and y are ints, this function essentially computes max(x,y), but fails in some cases.  List one such case.
 

b.  [Hard] Consider the following function:
def r(x, y): return (100 > x > y > 0) and (5 + r(y/2,x/3))
For all int values x and y such that r(x,y) returns 20, find the pair such that (x+y) is smallest.  For example, r(99, 95) returns 20, but 99+95 is definitely not the smallest such sum.