15-112 Spring 2013 Quiz 3-Redux
* 25 Minutes.  No calculators, no notes, no books, no computers.  * Show your work. Circle your answers.

1.    Quick Answers. [15 pts]
One (and only one) line of the following has a bug.  First, give an example of an argument s such that hasBalancedParentheses(s) will return the wrong answer.  Then, put a line through the line that contains the bug and provide the correct version of that line of code.
    def hasBalancedParentheses(s): # this version has a bug!
        p = 0
        for c in s:
            if (c == "("): p += 1
            elif (c == ")"): p -= 1
            if (p < 0): return False
        return True
 

2.    Code Tracing [40 pts]  Indicate what each will print.
def e():
    s = ("%d%5.1f%%" % (2, 34.567))
    print s, len(s)
    s = "a\t\\b\ncd\te"
    print s, len(s)
    return str("".islower()) +  str("a-b".islower())
print e()

def f(s):

    while (len(s) > 1):
        s = s[ s.find(s[-1]) : len(s)-1 : 2 ]
        print len(s), s
print f("abc"*4)

def g(s):

    u = ""
    for i in xrange(len(s)):
        for k in xrange(i):
            if (s[i] == s[k]):
                print i, k, s[k]
                u += str(i) + s[i]
    return u
print g("abcbcde")

def h(target):

    lo = 0
    hi = 20
    while (lo < hi):
        mid = (lo + hi)/2
        print mid,          # don't miss this line!
        if (mid**2 == target):
            return "Yes!"
        elif (mid**2 > target):
            hi = mid-1      # note the minus 1
        else:
            lo = mid+1      # note the plus 1
    return "No!"
print h(64)

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

def f(s):

    result = ""

    while (len(s) > 0):

        result += s[0:len(s):2]

        s = s[1:len(s):2]

    return (result == "abcdefg")

 

import string

def g(s):

    t = ""

    for i in xrange(0, len(s), 2):

        t += s[i+1] + s[i]

    return (t == string.digits[2:8])   

4.       Free Response [25 pts]
Rewrite the following function so that it works identically, only without any string methods (like s.foo()), functions (like foo(s)), or constants (like string.ascii_letters), except chr and ord. Also, give the function a well-chosen name.

def mysteryFunction(s):
    result = ""
    for c in s:
        if (c.islower()):
            c = c.upper()
        elif (c.isupper()):
            c = c.lower()
        result += c
    return result

 

5.  Bonus/Optional: [3 pts]  Indicate what the following will print:
s = "a%d%%d%%%d.1f" % (3, 4)
print s, "\t",
s %= (12, 3.456)
print s

 

6.  Bonus/Optional: [4 pts]  Find an argument for the following function that makes it return True.
def f(s):
    t = ""
    i = 0
    assert(s == s.lower())
    for c in s:
        j = string.hexdigits.find(c)
        assert(j >= 0)
        if (j == 15): j = -j
        i += j
        if (abs(j) < 14):
            t += string.ascii_letters[i]
    return (t == "Yep")