CSE 1310 - Midterm 2 Practice Questions


Problem 1

What does this program print?

for i in range(1, 5):
    for j in range(i):
        print i,  # The comma keeps the output on the same line
    print

Problem 2

Assume there is a file, file.txt. that contains the following lines. There is not a newline character at the end of the last line.

old pond...
a frog leaps in
water's sound

Given the above file contents, what does the file contain after running this code?

f = open('file.txt', 'a+')
x = f.readlines()
x.reverse()
f.write('\n')
for i in x:
    f.write(i)
f.close()

Problem 3

What does this program print?

def foo(s):
    if not type(s) is str:
        return None
    result = ''
    for i in range(0, len(s), 2):
        result = result + s[i]
    for j in range(1, len(s), 2):
        result = result + s[j]
    return result

## Main ##
print foo(5)
print foo('hweolrllod ')

Problem 4

What does this program print?

def foo(L):
    result = []
    for i in L:
        s = ''
        for j in range(0, len(i)):
            if j % 2 == 0:
                s = s + i[j].upper()
            else:
                s = s + i[j]
        result.append(s)
    return result

## Main ##
x = ['spam', 'eggs', 'bacon']
print foo(x)

Problem 5

Write a function, mirror(file1, file2), that takes two strings as arguments (two file names) and reads the lines in the first file, reverses the the order of the characters in each line and writes the result to file2. For example if the contents of file1 are:

hello
world

then the function should write file2 as:

olleh
dlrow

You can see it is a mirror image. Be careful of newline charaters. You can remove them and add your own back where needed:

line_from_file = line_from_file.strip('\n\r')
...
line_to_write = line_to_write + '\n'

Problem 6

def foo(l):
    if not bar(l) == True:
        return None
    s = ""
    for i in l:
        for x in i:
            s = s + str(x) + ' '
        s = s + '\n'
    return s

L = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print foo(L)

The above program takes the given list, verifies it is an appropriately structured list, and converts it to a 2D string representation (so it looks like a matrix). The code is incomplete; the verification function bar(l) has not been implemented. Write the function bar(l) that foo(l) can use to verify that its argument l is a list of three sublists, each of which contains 3 integers.


Problem 7

What does this program print? It will help to write out each variable and keep track of them as the code executes. Spaces are important. If it helps you, feel free to mark your spaces in your output with a character like a period.
for i in range(5, 0, -2):
    spaces = ''                   # This is an empty string
    end = (5-i)/2
    for j in range(0, end):
        spaces = spaces + ' '     # There is a single space in the quotes
    print spaces + '0'*i

for i in range(3, 6, 2):
    num_spaces = (5-i)/2
    print ' '*num_spaces + '0'*i  # There is a single space in the first quotes

Problem 8

If the contents of file.txt are
spam
eggs
bacon
what are its contents after running the following program?
fh = open('file.txt', 'r')
lines = fh.readlines()
fh.close()

for i in range(0, len(lines)):
    lines[i] = lines[i].strip('\r\n') # Removes newline characters

# Get maximum line length
m = 0
for line in lines:
    l = len(line)
    if l > m:
        m = l

fh = open('file.txt', 'w')
for i in range(0, m):
    s = ''
    for line in lines:
        if i >= len(line):
            s = s + ' '
        else:
            s = s + line[i]
        s = s + ' '
    fh.write(s + '\n')
fh.close()

Problem 9

Write a function, foo(start, end), that takes two integers as arguments and uses nested for loops to create a list that contains all the possible pairs of an odd number and an even number in the range start to end, inclusive. The function should verify that the inputs are integers and return None if either is not an integer. It should also return none if start > end. Otherwise, it will return the generated list of pairs. For example:
foo(1, 5)
will return:
[ [1, 2], [1, 4], [3, 2], [3, 4], [5, 2], [5, 4] ]
You can see that each odd number is paired with each even number in the appropriate range. It does not matter if the odd or the even number comes first.

Problem 10

Write a function, foo(s1, s2), that takes two strings as arguments, verifies that they are the same length and interleaves the characters of the two strings in the following manner:
print foo('hello', 'world')
This should print:
hweolrllod
The 'h' was taken from s1, the 'w' from s2, the 'e' from s1, the 'o' from s2, and so on.

Problem 11

Mr. Bugs is trying to write a function that takes two lists of strings as arguments, converts all the strings to lower case, and compares the two lists to see if they have any elements in common. If they have an element in common, the function should return True. Otherwise, it should return False. Why doesn't his code work and how can he fix it? The function is not supposed to do error checking, so that is not one of the bugs. There are multiple ways to fix the code; you only need to provide one.
def foo(x, y):
    x = x.lower()
    y = y.lower()
    for i in x:
        for j in y:
            if i == j:
                return True
        return False

## Main ##
a = ['Hello', 'World']
b = ['Spam', 'eggs', 'hello']
print foo(a, b)