DUMMY EXAM

The content of the dummy exam is representative for the content of the real exam of this course. The real exam will contain the same five tasks (Boolean expressions, General knowledge about Python, Spot the error, Tracing, and Code writing).

1. Boolean Expressions

Please determine for the following code snippets whether the output will be:

  1. False (of type bool)
  2. True (of type bool)

In [ ]:
# Exercise 1
print("home" != "homework")

In [ ]:
# Exercise 2
print("home"!="HOme".lower())

In [ ]:
# Exercise 3
print("home" not in "homework")

In [ ]:
# Exercise 4
print( (5 + 7) in [5, 1, 11, 7, 17, 13])

In [ ]:
# Exercise 5
print(100 != '100')

In [ ]:
# Exercise 6
print( (6 + 17) <= 22)

In [ ]:
# Exercise 7
print('a' not in 'hello world')

In [ ]:
# Exercise 8
d = {'1': 1, '2': 2}
print(1 in d)

In [ ]:
# Exercise 9
a_string = 'hello world'
any([a_string.replace('o', 'b', 1) == 'hellb wbrld',
     len(a_string) == (5+5),
     a_string[2] == 'e'])

In [ ]:
# Exercise 10
text='Chatbots Need A Personality'
print(text.count('a')==3)

In [ ]:
# Exercise 11
print( (1+4) > 5)

In [ ]:
# Exercise 12
d = {'1': 1, '2': 2}
print(len(d) == 2)

In [ ]:
# Exercise 13
l=[]
print(len(l)==None)

In [ ]:
# Exercise 14
letters = ['a','b','c','d']
numbers = [1,2,3,4,5]
print(letters[1] == 'a' or 4 in numbers)

In [ ]:
# Exercise 15
a_list = ['a', 'b', 'c', 'd']
print(a_list.pop() == 'd' and a_list[0] == 'a')

In [ ]:
# Exercise 16
a_list=['a', 'ab', 'abc', 'a', 'ac', 'abc']
a_set=set(a_list)

print(len(a_set)==3)

In [ ]:
# Exercise 17
a_list=['a', 'ab', 'abc', 'a', 'ac', 'abc']
a_str=''.join(a_list)
print(a_str[:5]=='aababc')

In [ ]:
# Exercise 18
def my_function():
    x=2
    
result=my_function()
print(result==2)

In [ ]:
# Exercise 19
def check_for_b(str1):
    if 'b' in str1:
        return True
    else:
        return False

str1="a string"
str2="b string"
print(check_for_b(str2)==False)

In [ ]:
# Exercise 20
a_dict = {'a': [1, 2], 'b': 'hi'}
print(len(a_dict['a']) <= 2)

In [ ]:
# Exercise 21
a_list=['a', 'b', 'c']
new_list=a_list.append('d')
other_list=a_list.append('e')
print(new_list!=other_list)

In [ ]:
# Exercise 22
letters = ['a', 'b', 'c', 'd']
numbers = set([1, 2, 3, 4, 5])
print(all([len(letters) <= 4,
           len(numbers) >= 5]))

2. General knowledge about Python

  1. Explain what the three values mean in Python’s slicing notation. For example, what does the following print? "Bananas are yummy."[1:-1:2]
  2. What is the difference between arguments (args) and keyword arguments (kwargs)?
  3. Assume that we have the following CSV line stored as a variable:
    line = "Vrije Universiteit,Amsterdam,The Netherlands"
    Write a single line of code that transforms this CSV line to a TSV line (both are strings).
  4. Explain what the continue, break and pass statements do.
  5. What are the two types of objects that you can define using curly braces {}?
  6. How can you turn a string representation of a number (e.g. ’1’) into an integer?
  7. What built-in function can you use to loop over all the whole numbers up to, for example, 100?
  8. What built-in function can you use to learn more about how to use a particular function?
  9. Which single change in the next line would print each name on a separate line? print(" ".join(["Alan", "Maria", "Paul"]))

  10. Why would anyone want to use sets instead of lists?

  11. What are the two ways to create an empty dictionary?
  12. What are the two building blocks of a dictionary?
  13. What would be printed with this code?

a_string = "python is awesome" print(a_string[7:11])

3. Spot the error

Below are ten pieces of code with a mistake in them. Please indicate the errors, and explain why they cause the code to break (you don’t need to know the exact error message). Each question is worth 2 points (one for pointing where exactly the mistake is, one for the explanation). For your convenience, we also printed line numbers next to each line of code. But we do expect you to be more explicit than just specifying the line number. (A one-sentence explanation is fine, though.)

Example question: where is the mistake here, and why doesn’t it work?

 my_list = [1,2,3]
 2nd_item = my_list[1]

Answer: The mistake is in the variable name 2nd_item (line 2), Python doesn’t allow variable names to start with numbers.


In [ ]:
# Exercise 1
shopping_list = {"butter": 1, "eggs": 12, "cheese": 1}
print(shopping_list[1])

In [ ]:
# Exercise 2
word = "bananas"
if word[0] = "b":
    print(word)

In [ ]:
# Exercise 3
def first_animal(animals)
    print(animals[0])

first_animal(["hedgehog", "fox", "eagle"])

In [ ]:
# Exercise 4
def replace_a_by_o(a_string):
    new_string = a_string.replace("a", "o")
    print(new_string)

replace_a_by_o('apples and bananas')
print(new_string)

In [ ]:
# Exercise 5
shopping_list = {["apples", "bananas"]: 2, "pineapples": 1}
for product in shopping_list:
    print(product)

In [ ]:
# Exercise 6
number = input("Please type a number: ")
if number < 2:
    print(number + " is lower than 2")
else:
    print(number + " is not lower than 2")

In [ ]:
# Exercise 7
number = 5413
if 1 in number:
    print("1 in", number)

In [ ]:
# Exercise 8
shopping_list = {["apples", "bananas"]: 2, "pineapples": 1}
for product in shopping_list:
    print(product)

In [ ]:
# Exercise 9
fruit = ["apple", "banana", "strawberry", "pineapple"]
fruit_string = ",".join(fruit)
fruit = fruit_string.split()
print(fruit[1])

In [ ]:
# Exercise 10
fruit = {"apple", "banana", "strawberry", "pineapple"}
fruit.append("mango")

4. Tracing

Below is a function that processes data from a morphological analyzer for Turkish. Here's an example of the data that needs to be processed:

'olmamak\tol<V><neg><vn:inf><N>\nolmamak\tol<V><neg><vn:inf><N><0><V><cpl:pres>\nolmamak\tol<V><neg><vn:inf><N><0><V><cpl:pres><3s>\n\n'

This data contains morphological information about the word olmamak (with two different analyses). The problem is that it's not yet suitable for further processing. So analyze_output() does that for us, returning the data in the form of a Python object that is easier to work with.

Please read this code (annotated with line numbers) and answer the questions below.


In [ ]:
def analyze_output(output):                          # 1
    "Analyze the output of the FST."                 # 2
    results = []                                     # 3
    for line in output.splitlines():                 # 4
        if line:                                     # 5
            word, analysis = line.split('\t')        # 6
            morph_data = analysis.split('<')         # 7
            base = morph_data[0]                     # 8
            rest = morph_data[1:]                    # 9
            morph_feats = []                         # 10
            for feature in rest:                     # 11
                morph_feats.append(feature[:-1])     # 12
            entry = {'word': word,                   # 13
                     'base': base,                   # 14
                     'features': morph_feats}        # 15
            results.append(entry)                    # 16
    return results                                   # 17

Suppose we call the function like this:


In [ ]:
output = 'olmamak\tol<V><neg><vn:inf><N>\nolmamak\tol<V><neg><vn:inf><N><0><V><cpl:pres>\nolmamak\tol<V><neg><vn:inf><N><0><V><cpl:pres><3s>\n\n'
result = analyze_output(output)
  1. What is the type and value of word on line 6, during the first iteration of the loop?
  2. What is the type and value of base on line 8, during the first iteration of the loop?
  3. What is the purpose of if line (line 5)? When does it evaluate to False?
  4. What is the type and value of entry (line 13) after the first iteration of the loop?
  5. What is the purpose of feature[:-1] on line 12? What does it do? (Use the first iteration of the loop as an example.)
  6. What is the type and value of results on line 17, at the end of the function?

5. Code writing

Below, you will find code descriptions. Please write the code according to these descriptions. Each piece of code is worth 5 points.

General information

Imagine that there are two files:

  • somewords1.txt
  • somewords2.txt

Each line in the file somewords1.txt contains one word (\n indicating the newline character), e.g.:

table\n
chair\n
tea\n
coffee\n
money\n
....

Each line in the somewords2.txt can contain multiple words. The words on a line are separated by a tab ('\t' in Python). '\n' indicates the newline character. The number of words on each line ranges from 1 to 4. Example line:

bed\tblanket\toffice\n
plate\tfork\n
jeans\n
....

Exercises

5.1. Please write the code to:

  1. define a set called unique_somewords2
  2. loop through the lines of file somewords2.txt
  3. remove the newline character from each line
  4. add each individual word in each line to unique_somewords2

In [ ]:

5.2. Please write the code to:

  1. define a set called filtered_uniquewords2
  2. loop through the lines of file somewords2.txt
  3. remove the newline character from each line
  4. checks for each word in the line if it:

    4.1. starts with the letter 'a'

    4.2. is longer than six letters

    4.3. is shorter than or equal to two letters

  5. If any of the checks in 4. are True for a word, we add the word to filtered_uniquewords2. Else, we do not add the word to filtered_uniquewords2.

In [ ]:

5.3. Please write the code to:

  1. define three sets: set_a, set_b, and set_rest
  2. loop through the lines of file somewords1.txt
  3. remove the newline character from each line
  4. perform the following actions:

    4.1. condition A: if the word starts with b or e -> add the word to set_a

    4.2. condition B: only if condition A is not met, but if the word consists of 10 characters -> add the word to set_b

    4.3. condition C: in all other conditions (hence not condition A and not condition B) -> add the word to set_rest


In [ ]: