Exam 2023-08-14

Here you find the questions, sample answers and marking guidelines for the exam 2023-08-14.

Information

Start by reading through all questions. Peter will not visit the exam. If you find any question unclear, ask one of the exam administrators (tentavakt in Swedish) to call Peter, and he will clarify the question over the phone.

Max score is 25 points.

  • For grade 3, 40% of max score (10 points) is required
  • For grade 4, 60% of max score (15 points) is required
  • For grade 5, 80% of max score (20 points) is required

During the test, you are only allowed to use:

  • The computer you sit at to only answer the questions on this exam (you may not run any other program)
  • A dictionary to translate to/from English from/to your native language
  • Pen and paper to sketch/write notes with (does not need to be submitted)

Write your answers in either English or Swedish. If you write your answers in Swedish, make sure to not introduce any translation confusement. Write proper sentences (spelling, upper/lower case characters, punctuation, etc.). Answers that do not do this good enough/are vague/are ununderstandable cannot receive full score on the questions.

Answers that are more or less copies of sample answers given to you or copies of text found somewhere else will be rewarded 0 points. Use your own words to answer the questions (does not apply to questions where you write code).

Good luck!

Question 1 (1p)

Question

Place the following lines of code in such order they can be executed (read underscores (____) as white-spaces/indentation (Inspera doesn't allow the text to begin with white-spaces 😞)).

  • ____if year < 2050:
  • ____year = 2023 + number_of_years
  • def program():
  • ____number_of_years = int(number_of_years)
  • program()
  • ____number_of_years = input("Enter number of years: ")
  • ________print("That is soon!")

You will get:

  • 1 point for all in correct order

Sample answer

def program():
    number_of_years = input("Enter number of years: ")
    number_of_years = int(number_of_years)
    year = 2023 + number_of_years
    if year < 2050:
        print("That is soon!")
program()

Marking guidelines

  • 1 point for all in correct order

Question 2 (1p)

Question

How many statements and expressions does the following code contain?

string = ""
for c in ["a", "b"]:
    string = string + c

Number of of statements: ...

Number of expressions: ...

You will get:

  • 1 point for both correct

Sample answer

Number of of statements: 3

Number of expressions: 7

Marking guidelines

  • 1 point for both correct

Question 3 (1p)

Question

What type of error does the code below contain? Syntax error, Logical error, Runtime error or no error at all? The purpose of the function is to compute the sum of the numbers it receives e.g. get_sum(2, 3) → 5.

def get_sum(number_1, number_2):
    return number_1 + number_1

You will get:

  • 1 point for correct answer

Sample answer

Logical error

Marking guidelines

  • 1 point for correct answer

Question 4 (1p)

Question

What values will be stored in the variables a and b after the following code has been executed?

a = 0
b = 10
while a < 2:
    a = a + 1
    b = b - 1

The variable a will store: ...

The variable b will store: ...

You will get:

  • 1 point for both correct

Sample answer

The variable a will store: 2

The variable b will store: 8

Marking guidelines

  • 1 point for both correct

Question 5 (1p)

Question

Write some Python code of your choice that contains a parameter and an argument, and explain what in the code that is the parameter, and what in the code that is the argument (write your explanations as Python comments).

You will get:

  • 1 point for both correct

Sample answer

def add_1(number): # number here is the parameter.
    return number + 1
five = add_1(4) # 4 here is the argument.

Marking guidelines

  • 1 point for both correct

Question 6 (1p)

Question

Bart is assigned the task to implement a program that prints this:

B-a-r-t

Bart writes the following code:

original_name = "Bart"
dashed_name = ""

for c in original_name:
    dashed_name = dashed_name + c
    dashed_name = dashed_name + "-"

print(dashed_name)

Bart's solution does not work as it should. Explain what output it currently produces, and suggest how the program can be fixed by adding a single if statement to the code (explain where in the code it should be added, and what the condition should be).

Sample answer

The code currently produces B-a-r-t-. That is, there's one - too much at the end. The if statement can be used to add - in each iteration in the loop except the last one. In the last iteration, c has the value "t", which it doesn't have in any other iteration, so checking that c is not equal to "t" is something we can use to add - in all iterations except the last one.

So instead of having:

dashed_name = dashed_name + "-"

We can use:

if c != "t":
    dashed_name = dashed_name + "-"

Marking guidelines

  • 0.33 points for current output
  • 0.33 points for where the if statement should be added
  • 0.33 points for the condition in the if statement

Question 7 (1p)

Question

The following expression:

range(0, 5, 2)

Creates a range. What is the sum of the integers in that range?

The sum is: ...

Sample answer

The sum is: 6

Marking guidelines

  • 1 point for correct answer

Question 8 (1p)

Question

What non-negative integers should be assigned to the variables x and y to slice out the values "a", "b", "c", "d" and "e" in the code below?

my_list = ["a", "b", "c", "d", "e"]
x = ?
y = ?
my_new_list = my_list[x:y]
# my_new_list should now be ["a", "b", "c", "d", "e"]

x: ...

y: ...

You will get:

  • 1 point for both correct

Sample answer

x: 0

y: 5

Marking guidelines

  • 1 point for both correct

Question 9 (1p)

Question

Write the following code:

my_list = [x < 10 for x in y if x != 0]

As statements using a loop instead. Your own code should have the exact same meaning as the code above.

Sample answer

my_list = []
for x in y:
    if x != 0:
        my_list.append(x < 10)

Marking guidelines

  • 1 point for an answer that is largely correct
  • Point reduction for errors:
    • -0.1 points for missing :
    • -0.1 points for spelling variable wrong
    • -0.25 points for indentation error
    • -0.25 points for indentation error
    • -0.5 points for writing the lines in wrong order

Question 10 (1p)

Question

Here is a quite complex structure with information about different movies:

movies = {
    "action": [
        {"name": "GoldenEye", "runtime": 110},
        {"name": "Mission Impossible", "runtime": 115},
        {"name": "Pearl Harbor", "runtime": 160}
    ],
    "drama": [
        {"name": "Titanic", "runtime": 180},
        {"name": "Love Actually", "runtime": 120}
    ]
}

Given this very structure, write an expression that evaluates to the runtime of the movie with the name Titanic, i.e. 180.

Note: Do not write a statement, and simply writing 180 is of course not OK; the value needs to be retrieved from the structure.

Sample answer

movies["drama"][0]["runtime"]

Marking guidelines

  • 0 points for an answer being a statement
  • 1 point for an answer that is an expression that works
    • -0.25 points for not having movies in the beginning
    • -0.25 points for missing a closing square bracket
    • -0.5 points for not having quotes around drama or runtime

Question 11 (1p)

Question

Suggest how the data in the Python code below:

heroes = [{
    "name": "Link",
    "color": "green"
}, {
    "name": "Mario",
    "color": "red"
}]

Can be expressed in XML format.

Note: This question is not about writing Python code, but XML code.

Sample answer

<heroes>
    <hero>
        <name>Link</name>
        <color>green</color>
    </hero>
    <hero>
        <name>Mario</name>
        <color>red</color>
    </hero>
</heroes>

Marking guidelines

  • 1 point for an answer that largely works
  • Point reduction for errors:
    • -0.25 points for putting values between < and >
    • -0.25 points for missing closing tag
    • -0.25 points for having quotes around value
    • -0.25 points for only having one <hero> element

Question 12 (1p)

Question

Suggest how the data in the Python code below:

heroes = [{
    "name": "Link",
    "color": "green"
}, {
    "name": "Mario",
    "color": "red"
}]

Can be expressed in CSV format.

Note: This question is not about writing Python code, but CSV code.

Note: Do not write any extra characters not needed.

Sample answer

Link,green
Mario,red

Marking guidelines

  • 1 point for an answer that largely works
  • Point reduction for errors:
    • -0.25 points for writing extra characters not needed (such as spaces and ")

Question 13 (1p)

Question

What will be stored in the variable sum after the following code has been executed?

def a(number):
    number = number + 1

def b(list):
    for number in list:
        number = number + 3

def c(list):
    for i in range(len(list)):
        list[i] = list[i] + 2

my_list = [0, 0]

c(my_list)
a(my_list[0])
b(my_list)
a(my_list[0])

sum = my_list[0] + my_list[1]

sum: ...

Sample answer

sum: 4

Marking guidelines

  • 1 point for correct answer

Question 14 (1p)

Question

Implement the function get_type(), which receives a none-negative integer as argument representing the age of a human, and should return the string:

  • "baby", if the age is between 0 and 1 (both inclusive)
  • "kid", if the age is between 2 and 12 (both inclusive)
  • "teen", if the age is between 13 and 19 (both inclusive)
  • "adult" otherwise

Sample usage:

get_type( 1)   →   "baby"
get_type(12)   →   "kid"
get_type(13)   →   "teen"
get_type(50)   →   "adult"

Sample answer

def get_type(age):
    if age <= 1:
        return "baby"
    elif age <= 12:
        return "kid"
    elif age <= 19:
        return "teen"
    else:
        return "adult"

Marking guidelines

  • 1 point for a solution that largely works
  • Point reduction for small mistakes or doing weird things:
    • -0.1 points for indentation error
    • -0.25 points for using a while loop
    • -0.25 points for printing instead of returning value
    • -0.5 points for using input()

Question 15 (2p)

Question

Write a program that keeps asking the user to enter an integer until the user enters stop. The program should then print each even integer the user entered back to the user, each on its own line. To check if an_integer is even, you can use the expression an_integer % 2 == 0. When running the program, it can look like this (bold text represents text entered by the user).

Enter an integer or stop: 8
Enter an integer or stop: 3
Enter an integer or stop: 4
Enter an integer or stop: 9
Enter an integer or stop: 5
Enter an integer or stop: 6
Enter an integer or stop: stop
The even integers you entered are:
8
4
6

Note: The output should look precisely as in the example above (including white-spaces, but with the exception of the boldness from the input, of course).

Note: You can expect the user to actually enter an integer or stop (no error handling needed).

Sample answer

even_integers = []

entered_text = ""

while entered_text != "stop":
    
    entered_text = input("Enter an integer or stop: ")
    
    if entered_text != "stop":
        
        entered_integer = int(entered_text)
        
        if entered_integer % 2 == 0:
            even_integers.append(entered_integer)

print("The even integers you entered are:")

for even_integer in even_integers:
    print(even_integer)

Marking guidelines

  • 2 points for a program that largely works
  • Point reduction for small mistakes or doing weird things:
    • -0.25 points for using the entered integer as an integer before converting it to an integer
    • -0.25 points for having code doing unnecessary things

Question 16 (2p)

Question

Implement the function contains_two_odd, which receives a list of integers, and returns:

  • True if precisely two of the integers in the list are odd
  • False otherwise

To check if an_integer is odd, you can use the expression an_integer % 2 == 1.

Write two different implementations of the function: one using a while loop, and another one using a for loop.

Sample usage:

contains_two_odd([2, 1, 0, 3]) → True
contains_two_odd([1, 1, 1, 2]) → False
contains_two_odd([1, 2, 4]) → False
contains_two_odd([]) → False
contains_two_odd([1, 1]) → True

Sample answer

def contains_two_odd(integers):
    number_of_odd_integers = 0
    for integers in integers:
        if an_integer % 2 == 1:
            number_of_odd_integers += 1
    return number_of_odd_integers == 2

def contains_two_odd(integers):
    number_of_odd_integers = 0
    index = 0
    while index < len(integers):
        if integers[index] % 2 == 1:
            number_of_odd_integers += 1
        index += 1
    return number_of_odd_integers == 2

Marking guidelines

  • 1 point for the function with the for loop largely working
  • 1 point for the function with the while loop largely working

Question 17 (3p)

Question

Below is some data about houses owned by some humans.

houses = [
   {"owner": "Alice", "name": "Alice's Palace", "number_of_rooms": 9, "number_of_windows": 20},
   {"owner": "Alice", "name": "Alice's Home",   "number_of_rooms": 3, "number_of_windows": 5},
   {"owner": "Alice", "name": "Alice's Cabin",  "number_of_rooms": 1, "number_of_windows": 4},
   {"owner": "Bob",   "name": "Bob's Home",     "number_of_rooms": 4, "number_of_windows": 16},
   {"owner": "Bob",   "name": "Bob's Cabin",    "number_of_rooms": 1, "number_of_windows": 1}
]

It's hot in the summer, and it costs money to cool down the houses. To cool down a single house costs:

  • 200 SEK each month...
  • ...+ 20 SEK each month for each room in the house...
  • ...+ 60 SEK each month for each window in the house

Write code that first computes who of Alice and Bob that owns the most expensive house to cool down. Then write code that computes how much that person needs to pay for cooling down all of his/her houses in total.

Note: Your code should still work as expected if one adds/removes houses to/from the list. Alice and Bob are the only ones who can own a house.

Sample answer

cooling_down_base_cost_per_house = 200
cooling_down_cost_per_room = 20
cooling_down_cost_per_window = 60

def get_cooling_down_cost(house):
    return (
        cooling_down_base_cost_per_house +
        cooling_down_cost_per_room * house["number_of_rooms"] +
        cooling_down_cost_per_window * house["number_of_windows"]
    )

# First compute the most expensive house to cool down.
most_expensive_house = houses[0]

for house in houses:
    if get_cooling_down_cost(most_expensive_house) < get_cooling_down_cost(house):
        most_expensive_house = house

owner = most_expensive_house["owner"]

# Then compute how much that person pays for all his/her houses.
total_cost = 0

for house in houses:
    if house["owner"] == owner:
        total_cost += get_cooling_down_cost(house)

print(owner+" has the most expensive house to cool down, and "+owner+" pays in total "+str(total_cost)+" to cool down all the houses.")

Marking guidelines

  • 1.5 point for computing who has the most expensive house to cool down
  • 1.5 point for computing how much that one pays in total for all houses

Question 18 (2p)

Question

The class Counter represents a counter/number that can be changed.

The class has the following constructor/methods:

Constructor/MethodDescription
Counter(start_number)Creates a new counter starting on the given start_number
inc()Increments the counter by 1
reset()Sets the counter to the start_number it received through its constructor
set_to(new_number)Sets the counter to new_number
get_number()Returns the counter's current number

Write a program making use of the class. In the program, you should continue to ask the user to enter commands that modify the counter (see the sample usage below) until the user enters stop. After each command, the counter's new value should be shown to the user.

Sample usage:

Enter start value: 5
Enter command (inc/reset/set/stop): inc
The counter is currently 6.
Enter command (inc/reset/set/stop): inc
The counter is currently 7.
Enter command (inc/reset/set/stop): reset
The counter is currently 5.
Enter command (inc/reset/set/stop): inc
The counter is currently 6.
Enter command (inc/reset/set/stop): set
Enter number: 0
The counter is currently 0.
Enter command (inc/reset/set/stop): inc
The counter is currently 1.
Enter command (inc/reset/set/stop): reset
The counter is currently 5.
Enter command (inc/reset/set/stop): stop
The counter is currently 5.

Note: The output should look precisely as in the example above (including white-spaces, but with the exception of the boldness from the input, of course). It is OK if the percentage numbers on the last two lines show decimal numbers.

Note: No error handling is needed; you can expect the user to always enter valid values.

Sample answer

start_number = int(input("Enter start value: "))
counter = Counter(start_number)

entered_command = ""

while entered_command != "stop":
    
    entered_command = input("Enter command (inc/reset/set/stop): ")
    
    if entered_command == "inc":
        
        counter.inc()
        
    elif entered_command == "reset":
        
        counter.reset()
        
    elif entered_command == "set":
        
        new_number = int(input("Enter number: "))
        counter.set_to(new_number)
        
    print("The counter is currently "+str(counter.get_number())+".")
    

Marking guidelines

  • 2 points for an answer that largely works

Question 19 (2p)

Question

The class Counter represents a counter/number that can be changed.

The class has the following constructor/methods:

Constructor/MethodDescription
Counter(start_number)Creates a new counter starting on the given start_number
inc()Increments the counter by 1
reset()Sets the counter to the start_number it received through its constructor
set_to(new_number)Sets the counter to new_number
get_number()Returns the counter's current number

Implement the class per the description above.

Sample answer

class Counter:
    
    def __init__(self, start_number):
        self.start_number = start_number
        self.number = start_number
    
    def inc(self):
        self.number += 1
    
    def reset(self):
        self.number = self.start_number
    
    def set_to(self, new_number):
        self.number = new_number
    
    def get_number(self):
        return self.number

Marking guidelines

  • 0 points to answers not using the self parameter at all, or using class variables instead of instance variables
  • 2 points for a solution that largely works