Practice problems: Week 2ΒΆ

The purpose of these problems is to allow you to test you understanding of the material we have covered so far. It is intended to take an hour or so, assuming you have done the reading.

To get started run git pull upstream master, which will pick up a directory named pp2.

The problems are broken up into two parts: a set of “be-a-computer” warm-up exercises and a set of programming problems. You should do the warm-up exercises by hand. You can check your answer by running the Python program warmup.py in pp2. We will be using a system named Kattis for the programming problem. Kattis is a website that allows students to submit solutions to programming problems, and have them evaluated automatically by running a series of test cases on the submitted solutions. You can find information about how to use Kattis here. You can find the skeleton code needed for the programming problems in pp2.

Warm-up exercise #1: What is the output of the following code?

def F1(i, j) :
    print("F1({}, {})".format(i, j))
    F2(j, i+j)
    print("F1: i = {}, j = {}".format(i, j))
    

def F2(i, j) :
    print("    F2({}, {})".format(i, j))
    k = F3(i, j)
    print("    F2: i = {}, j = {}, k = {}".format(i, j, k))
    

def F3(i, j) :
    print("        F3({}, {})".format(i, j))
    i = i+j
    j = i+2*j
    k = 2*i+3*j
    print("        F3: i = {}, j = {}, k = {}".format(i, j, k))
    return k
    

print("Warmup exercise 1:")
F1(1, 1)
print()

Warm-up exercise #2: What is the output of the following code?

def mystery1(l):
    rv = []
    for x in l:
        rv = [x] + rv
    return rv

print("Warmup exercise 2:")
l = [0, 1, 2, 3, 4]
nl = mystery1(l)
print("l: ", l)
print("nl: ", nl)

Warm-up exercise #3: What is the output of the following code?

def mystery2(l):
    rv = []
    for i in range(len(l)-1, -1, -1):
        rv.append(l[i])
    return rv

print("Warmup exercise 3:")
l = [0, 1, 2, 3, 4]
nl = mystery2(l)
print("l: ", l)
print("nl: ", nl)

Programming problem #1: Within range

Programming problem #2: Count negative

Programming problem #3: List negate

Here are a couple problems for those of you who like a challenge!

Challenge exercise: What is the output of the following code?

def mystery3(l):
    n = len(l)
    for i in range(n // 2):
        t = l[i]
        l[i] = l[n-i-1]
        l[n-i-1] = t


print("Challenge exercise:")
l = [0, 1, 2, 3, 4]
mystery3(l)
print("l: ", l)

Challenge programming problem: A tricky problem