15-112 Fall 2012 Homework 7b
Physical copy due Sunday, 14-Oct, at 10pm

Read these instructions first!

1.  Reasoning About Code  [25 pts; 5 pts each]

For each of the following functions, find values of the parameters so that the functions will return True.  You should assume that x, y, and z are ints, and that s is a string.  Hint:  reason your way through this.  How you find your answer is just as important, if not more so, than what the answer is!  While you may confirm your answer by running it in a Python interpreter, do not use the Python interpreter at all when solving the problem.  You will be given similar problems such as these on written quizzes without access to Python interpreters!  Also, consider only the possible inputs.  For example, if you are given that x+y==16, since x>y>0, we only need consider (15,1), (14,2), ..., (9,7).  That's only 7 (x,y) points in total, one of which must be correct!  Also, CIRCLE YOUR ANSWERS!

def f1(a):
    n = len(a)
    assert(n == 3)
    b = [([0]*n) for row in xrange(n)]
    for i in xrange(n):
        b[i][i] = i
        b[i][n-1-i] = i+1
    return (b == a)       


def f2(a):
    assert ((len(a) == 2) and (len(a[0]) == 3))
    for c in xrange(len(a[0])):
        s = 0
        for r in xrange(len(a)):
            if (r > 0): assert(a[r][c] != a[r-1][c])
            s += a[r][c]
        assert(s == 5)
    return True  



def f3(a):
    assert(len(a) * len(a[0]) == 6)
    x = 0
    for r in xrange(3):
        for c in xrange(2):
            if ((r+c) % 2 == 0):
                x = 10*x + (a[r][c] % 10)
            else:
                assert(a[r][c] == 0)
    return (x == 42)


def f4(a):
    (rr,cc,r,c) = (len(a), len(a[0]), 0, 1)
    assert((rr*cc == 15) and (rr>cc>1))
    for i in xrange(rr*cc):
        assert(a[r][c] == i%7)
        if (c == 0): (r,c) = ((r-1)%rr,cc-1)
        else: (r,c) = (r, c-1)
    return True


def f5(c):
    # Note that c is a non-rectangular ("ragged") 2d list!
    n = len(c)
    a = [[1]]
    for i in xrange(1,n):
        a.append([1]*(1+len(a[i-1])))
        for j in xrange(1,i):
            a[i][j] = a[i-1][j-1]+a[i-1][j]
    assert(a == c)
    b = [1]
    for i in xrange(1,n):
        s = 0
        for j in xrange(i):
            if (j < len(a[i-j])):
                s += a[i-j][j]
        b.append(s)
    return b[-1] == 8


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