CSE 1310 - Exams - Midterm 3 Practice Questions


Problem 1

What does this program print?

for i in range(1, 5):
    for j in range(i):
        print(i)  

Problem 2

Assume there is a file called file1.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 file file2.txt contain after running this code?

f = open('file1.txt', 'r')
x = f.readlines()
x.reverse()
f.close()

f = open('file2.txt', 'w')
for i in x:
    i = i.strip()
    print(i, file=f)
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 ##
def main():
    print(foo(5))
    print(foo('hweolrllod '))

main()

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 ##
def main():
    x = ['spam', 'eggs', 'bacon']
    print(foo(x))

main()

Problem 5

Write a function mirror(file1, file2), that takes two strings as arguments (two file names) and reads the lines in file1, 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()
...
line_to_write = line_to_write + '\n'

Problem 6

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

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

main()

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(list1) has not been implemented. Write the function bar(list1) that foo(list1) can use to verify that its argument list1 is in the expected format:


Problem 7

What does this program print? It will help to write out each variable and keep track of them as the code executes. The number of dots printed at each location is important.
for i in range(5, 0, -2):
    dots = ''                   # This is an empty string
    end = int((5-i)/2)
    for j in range(0, end):
        dots = dots + '.'     
    print(dots + '0'*i)

for i in range(3, 6, 2):
    num_dots = int((5-i)/2)
    print('.'*num_dots + '0'*i)  

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() # 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 + ' '
    print(s, file=fh)
fh.close()

Problem 9

What does the following program print?
def main():
    d = {1 : "car",
         2 : "house",
         3 : "boat",
         4 : "dog",
         5 : "kitchen"} 
    L = list(d.keys()) 
    i = 0 
    while i < len(L):
        k = L[i]
        if k < 3 : 
            d[ d[k] ] = "zebra"
        i += 1
    for k in d :
        print(k, d[k]) 

main()


Problem 10

Write a function, foo(start, end), such that: For example:
foo(1, 5)
can 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. The order in which the pairs appear also does not matter.

Problem 11

Write a function, foo(s1, s2), such that: For example:

Problem 12

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 ##
def main():
    a = ['Hello', 'World']
    b = ['Spam', 'eggs', 'hello']
    print(foo(a, b))

main()

Problem 13

Write a function foo(L_keys, L_values) that builds a dictionary from a list of keys, L_keys, and a list of values, L_values. It takes as input the two lists and returns the dictionary. The first element in L_keys will be paired with the first element in L_values and that key-pair value will be inserted in the dictionary. Same goes for the second elements in the lists and so on. If the two lists have different length, the function returns None.

For example:

Don't worry about any other error checking than what was explicitly stated above. Do not write the main function (there is no credit for it). Your function needs to build the dictionary. It does NOT have to print the elements of the dictionary in the order shown in this example (dictionary objects reorder themselves...).

Problem 14

Write a function foo(d1) that takes as argument a dictionary d1 mapping strings to numbers, and prints all the keys of the dictionary in order of values. For example: Do not worry about error checking on this function. In other words, you will NOT be graded on what the function does when the input is not a dictionary, or when the keys are not strings, or when the values are not numbers.