FP2 practical mock exam — programme in Python and Java right here, with a mark and comments like the VPL

Do you know classes and linked lists but freeze when the VPL gives you a 4 and you cannot tell why? This mock exam reproduces the FP2 practical exams inside the website: you pick the exam (the three continuous-assessment ones or the resit) and a version, and you programme in an environment with the SergioLearns look that runs Python and Java in your browser. Just like in the exam, you press Evaluate and get a mark out of 10 with a comment for each failing test («with an empty queue, serve() — you get … ; expected None»).

There are 15 original exercises: three versions (A, B and C) of each exam and, in the resit, one Python and one Java exercise per version. They are all written for this mock exam, with the same format, difficulty and timings as the real ones. Before the mock exam I explain what the exam is like; afterwards, how it is marked, the cases that fail most in linked lists and the Python and Java cheat sheets, which were what you could check.

Take the mock exam

Pick the exam and the version (or «Random»), press Start and work as in aep26: complete the class file, try it with the tryout file and evaluate when you think it is ready. When you press Hand in (or time runs out) the last version of your code is marked.

The mock exam needs JavaScript. Below you will find what the exam is like and what each exercise covers.

The first time you press Run or Evaluate, the browser downloads Python (about 12 MB) or Java (about 8 MB). It takes a few seconds; after that it is fast and it stays saved for your next visit.

Your code never leaves your computer: it runs in your browser and is saved there while you work (if you reload the page, it is still there). The draft is deleted when you hand in.

What the FP2 practical exam is like

The FP2 practical exams are done in VPL, aep26’s programming activity. Each one is one exercise: a class you have to complete, with a statement that says which methods and properties it has, an example with its output and some automatic tests that give the mark.

ExamLanguageWhat it asksTimeMarks
Exam 1PythonA class with hidden attributes, properties, class attributes and methods, exceptions and __str__75 min10
Exam 2PythonA linked list (singly or doubly linked) that inherits from ContainerBase75 min10
Exam 3JavaA linked list that extends ContainerBase75 min10
ResitPython + JavaA linked list in each language120 min5 + 5

Each exam had several sittings with different statements (that is why there are versions A, B and C here), but all with the same file structure. This drawing is exactly what you will see in the environment:

The parts of the environmentThree files: the marked module, the manual tests file and the given ones. Run executes the tests file and shows the console; Evaluate runs the exam tests on your module and gives the mark with a comment per failure.What you see in the environmentbooking.pymarked · you complete ittryout.pynot marked · manual testscourts.pygiven · read-only  Run  EvaluateCONSOLEprint(…) → textEVALUATION7.5 / 10  empty list → None  6 tests passedThe first 10 evaluations of each exercise are free
Look at the arrows: Run only looks at your tests file; Evaluate only looks at the module you complete.
  • The marked file (booking.py, turns.py, BoxStack.java…): you complete it. The tests only look at this one.
  • The tryout file (tryout.py or Tryout.java; in the real exam, prueba.py or Pruebas.java): it has the statement’s example and you can change it as you like. It is not marked, but if it has an error you cannot run.
  • The given classes (ContainerBase, Node, Song, the class that provides the data…): already written and not to be touched. ContainerBase is the one that draws the list with ➡, ⬅ and -> when you print it.

Using a Python list (or a Java ArrayList) to store the data «because it is easier». In exams 2, 3 and the resit it is forbidden: the tests detect it and take those marks away, and in the real exam you risk a zero.

What each exam covers

ExamWhat you have to masterPractice with the exercises of
Exam 1 (Python)Encapsulation with __, @property (read-only and with a setter), @classmethod and class attributes, raise ValueError, __str__ and __len__Classes in Python · Inheritance in Python · Exceptions in Python
Exam 2 (Python)Nodes, first and last, inserting and removing anywhere, doubly linked lists, __iter__ as a generator, inheriting from ContainerBaseLinked lists in Python · Iterators and generators
Exam 3 (Java)The same in Java: extends ContainerBase, null, equals, returning arrays, doubly linked listsClasses and objects in Java · Inheritance in Java · Iterators in Java
ResitOne linked-list exercise in Python and another in JavaAll of the above

If the theory is what fails, the FP2 theory mock exam uses each topic’s quizzes.

How it is marked

The VPL has no rubric: the mark is the tests’ mark. Each test checks one specific thing (the empty list, removing the last one, that last is updated…) and has a weight; your mark is the sum of the weights of the tests you pass, out of 10. Each failing test comes with its comment, for example:

✗ cancel() of the last one updates last  (1.5 p)
  After cancelling the last one — you get '➡[#1 Ana]->[#2 Luis]->None'; expected '➡[#1 Ana]->[#2 Luis]⬅->None'.

That comment already tells you the bug: after removing the last one, last still pointed to the removed node, so the list no longer marks it with ⬅, and the next «add at the end» would hook onto a node that is no longer in the list.

The trap of pressing Evaluate non-stop. In the real exam, the first 10 evaluations of each exercise were free, and from then on each new evaluation subtracted 0.1 from the exercise mark. The mock exam works the same way (the counter is shown next to the environment’s tabs):

Penalty per evaluationBars of the maximum mark of an exercise: 10 up to the tenth evaluation and 0.1 less for each one from the eleventh, down to 9 with 20 evaluations.Maximum mark of an exercise by how many times you press Evaluate109.591234567891011121314151617181920evaluations20 → max 91 to 10 → free
Purple bars cost nothing; each coral bar subtracts 0.1: evaluating to check is fine, evaluating blindly gets expensive.

Doing the sums by hand: with 12 evaluations you lose 2 × 0.1 = 0.2; with 15, 5 × 0.1 = 0.5; and with 20, a whole mark. In the resit each exercise is worth 5, so its mark out of 10 is multiplied by 0.5. For example, an 8 in Python with 12 evaluations (8 − 0.2 = 7.8) and a 6 in Java with 5 evaluations give 7.8 × 0.5 + 6 × 0.5 = 3.9 + 3 = 6.9.

Use Run as much as you like (it does not count) and keep Evaluate for when the tryout file already gives what the statement asks for. Each evaluation should teach you something new, not be a way to «see if it gets through».

How to use the environment

  1. Read the whole statement and look at the given classes (the tabs with a padlock): which attributes they have and what they are called.
  2. Write the skeleton first: every method header and property with pass (Python) or any return (Java). In Java, if a method the tests use is missing, nothing compiles and you get a 0.
  3. Run the tryout file (Run button or Ctrl+Enter) and compare with what the statement says.
  4. Evaluate and read the comments: each one tells you which case fails and what was expected.
  5. Repeat 3 and 4 wisely. Reset goes back to the starting code; Stop cuts a programme that does not finish; Cheat sheet opens the reference material.

A few things worth knowing about the environment:

  • Python is real CPython 3.14 (Pyodide), so it behaves as on your computer: same errors, same exceptions and the traceback with the line of your file.
  • Java is compiled with OpenJDK’s javac and run with TeaVM, all in the browser. It has one difference that matters: a NullPointerException or an index outside an array stop the programme (they cannot be caught with catch) and the browser does not give the line number. The environment tells you which one it was, and when evaluating it marks that test as failed and carries on with the rest.
  • If a programme does not finish (the classic while that does not move on to the next node), it is stopped after a few seconds and the test shows «it takes too long».

In Java, comparing strings with ==. The tests sometimes use new String("Ana"), which is another object even though it has the same text: with == your search does not find it; with equals, it does.

Strategy for the 75 minutes

TimeWhat to do
0-10 minRead the statement and the given classes; write the full skeleton
10-25 minThe easy part: initialiser, add at the end, size, properties. Run
25-55 minThe hard part: remove, search, split or re-place. Run with the odd cases
55-70 minEvaluate, read the comments and fix
70-75 minCheck nothing is left half-written that stops it from running

In the resit you have 120 minutes for both: split them in half and do not leave either one without a skeleton, because an exercise that does not compile is worth 0 even if it is almost done.

The cases that fail most in linked lists

Almost every bug in exams 2 and 3 is in removing a node. You have to look at three things: who pointed to it (first or the previous node’s next), and, if it was the last one, last. In the drawing, the list is 3 → 5 → 8 → 9:

Removing a node: the three casesThree rows with the list 3, 5, 8, 9. Removing the first one moves first; removing a middle one makes the previous one jump over it; removing the last one sets the previous next to None and moves last back.1 · Remove the first one (prev is None)first = node.next3589firstlast2 · Remove a middle oneprev.next = node.next3589first · prevlast3 · Remove the last one (it also moves last)prev.next = None · last = prev358None9firstprev · last
Look at which label changes in each row: first in row 1, only one next in row 2, and next plus last in row 3.

The pattern in Python, with the previous node (prev) and the current one (node):

prev, node = None, self.first
while node is not None and node.value != wanted:
    prev, node = node, node.next      # move both at the same time
if node is not None:                  # found
    if prev is None:                  # case 1: it was the first one
        self.first = node.next
    else:                             # case 2: the previous one jumps over it
        prev.next = node.next
    if node is self.last:             # case 3: it was the last one
        self.last = prev

And in Java, the same but with null and equals:

Node prev = null, n = first;
while (n != null && !n.value.name.equals(name)) {   // equals, never ==
    prev = n;
    n = n.next;
}
if (n != null) {
    if (prev == null) first = n.next; else prev.next = n.next;
    if (n == last) last = prev;
}

The five cases you must always test, in this order: empty list, a single element, the first one, the last one (and then add another, to see that last is right) and an element that does not exist. The exam tests go straight for them.

In a doubly linked list every change touches two links: prev.next and next.prev. If you only update one, the list walks fine forwards but breaks backwards, and the undo() or previous() tests catch it.

Common mistakes

  • Not updating last when removing the last one or emptying the list: the next «add at the end» hooks onto a ghost node.
  • Moving on after removing in a multiple removal: if you remove node.next, the new node.next may be another one that also has to go.
  • Public attributes in exam 1: the statement asks you to encapsulate; use self.__x and properties.
  • Counting in the object what belongs to the class: self.total += 1 creates a new attribute in the object; the class counter is changed with Class.total.
  • type(x) is int versus isinstance: isinstance(True, int) is True; if the statement says «an integer», True should not count.
  • Signatures different from the statement’s (name, parameters or return type): in Java the tests do not compile and you get a whole 0.

Watch it step by step in Python Tutor

Python Tutor runs the code line by line and draws the objects and the arrows between them: it is the best way to see a linked list. Choose Python 3, paste this programme (it removes every 5 from the list 3 → 5 → 5 → 8) and step through with Next:

class Node:
    def __init__(self, value, next=None):
        self.value = value
        self.next = next


first = Node(3, Node(5, Node(5, Node(8))))   # 3 -> 5 -> 5 -> 8
target = 5
prev, node = None, first
while node is not None:
    if node.value == target:
        if prev is None:
            first = node.next          # it was the first one
        else:
            prev.next = node.next      # prev does not move: the next one may be another 5
    else:
        prev = node
    node = node.next

values, node = [], first
while node is not None:
    values.append(node.value)
    node = node.next
print(values)
[3, 8]

What to watch:

  1. When first is created, Python Tutor draws four boxes chained by the next arrow; the last one points to None.
  2. When node reaches the first 5, notice that prev is still on the 3: the line prev.next = node.next makes the 3’s arrow jump the 5.
  3. On the next loop node is on the second 5 and prev is still on the 3 (it did not move when removing): that is why the second 5 is also removed properly.
  4. At the end, no arrow reaches the two nodes holding 5 any more: for the list they no longer exist, although Python Tutor keeps showing them until the garbage collector cleans them up.

Cheat sheet: what you could check

In the exam you could check a Python cheat sheet and a Java one. These are ours, rewritten with what you really use in the exercises. You also have them inside the environment, with the Cheat sheet button.

Python cheat sheet FP2

What you could check in the exam, in our own words: syntax, classes, exceptions and the linked-list patterns.

The basics

x = 5; y = 2.5; s = "hello"; ok = Trueint, float, str and bool
7 // 2 → 3 7 % 2 → 1 2 ** 3 → 8floor division, remainder and power
a, b = b, aswaps without a temporary variable
f"{total:.2f}€" f"{n:>5}" f"{x!r}"f-string: 2 decimals, right-align, repr
if x > 0 and not empty: … elif …: … else: …and, or, not (no && or ||)
for i in range(2, 10, 2): … while n: …range(start, end not included, step)

Strings

s.upper() s.lower() s.strip() s.title()return a new string (they are immutable)
s.split(",") ", ".join(items)split into a list / join a list
s.find("ab") → -1 si no está s.count("a")find does not raise; index does
s.startswith("P-") s.endswith(".py") "ab" in scheck start, end or containment
s[1:4] s[-1] s[::-1]slice, last character, reversed

Lists, tuples, dicts and sets

l.append(x) l.insert(0, x) l.pop() l.remove(x)append, insert at a position, pop, remove a value
sorted(l, key=len, reverse=True) l.sort()sorted returns another; sort changes the same one
t = (1, 2) a, b = ttuple: immutable; it unpacks
d.get(k, 0) d.items() d.pop(k) k in dget with a default; in looks at the keys
d[k] = d.get(k, 0) + 1counting (counter pattern)
{x for x in l} a | b a & b a - bset: no repeats; union, intersection, difference
[x * 2 for x in l if x > 0]list comprehension with a filter

Functions

def f(a, b=1, *args, **kw): return a + bdefault and variable parameters
lambda x: x[1]one-line function (for key=)
sum(l) max(l) min(l, key=…) len(l) any(…) all(…)handy built-in functions
enumerate(l, 1) zip(a, b) reversed(l)index + value, pair up, walk backwards

Classes

class Order: total_closed = 0 def __init__(self, id): self.__id = idclass attribute and hidden attribute (__ = name mangling)
@property def id(self): return self.__idread-only property
@id.setter def id(self, v): if not v: raise ValueError("…") self.__id = vwritable property with a check
@classmethod def closed(cls): return cls.total_closedclass method: it uses cls, not self
@staticmethod def check(x): …static method: neither self nor cls
Order.total_closed += 1change the class attribute (with self. you would create another one in the object)

Special methods

__str__ → print(obj) __repr__ → en listastext for people / for debugging
__len__ → len(obj) __contains__ → x in objsize and membership
__eq__ __lt__ __add__comparison and operators (==, <, +)
def __iter__(self): nodo = self.first while nodo: yield nodo.value nodo = nodo.next__iter__ as a generator: for x in obj

Inheritance and exceptions

class Child(Base): def __init__(self, a, b): super().__init__(a)inherit and call the parent initialiser
isinstance(x, Base) type(x) is intis it that class (or a child)? / exactly that type?
raise ValueError("invalid quantity")raise an exception with a message
try: … except ValueError as e: print(e) else: … finally: …else if there was no error; finally always
class BalanceError(Exception): passcustom exception

Linked lists

nodo = self.first while nodo is not None: … nodo = nodo.nextwalk it: do not forget to move on
n = self.Node(x) if self.first is None: self.first = n else: self.last.next = n self.last = nappend at the end with last
if prev is None: self.first = nodo.next else: prev.next = nodo.next if nodo is self.last: self.last = prevremove a node: first, prev and last
self.first = self.Node(x, self.first)add at the start in one line
Casos: vacía, un elemento, primero, últimoalways test them before Evaluate

Java cheat sheet FP2

What you could check in the exam, in our own words: syntax, classes, exceptions and the linked-list patterns.

The basics

int n = 5; double d = 2.5; char c = 'a'; boolean ok = true; String s = "hello";primitive types and String
7 / 2 → 3 7 % 2 → 1 7 / 2.0 → 3.5between integers division is integer
(int) 5.9 → 5 Integer.parseInt("42") String.valueOf(3)conversions
x = cond ? a : b; final int MAX = 10;ternary operator and constant
System.out.println(x); System.out.printf("%.2f%n", d);print (with a newline) and formatted
String.format("%5d|%-6s|%.1f", 42, "ab", 3.14)%d integer, %s text, %.1f decimal; – left-aligned

Control flow

if (a > 0 && !empty) { … } else if (…) { … } else { … }&&, ||, !; always braces
for (int i = 0; i < n; i++) { … } for (int x : array) { … }classic for and for-each
while (cond) { … } do { … } while (cond);do runs at least once
switch (op) { case "+" -> r = a + b; default -> r = 0; }arrow switch (no break)
break; continue; return x;exit, skip to the next iteration, return

Strings

s.length() s.charAt(0) s.substring(1, 4) s.indexOf("ab")length, character, slice [1, 4), position (-1 if absent)
s.equals(t) s.equalsIgnoreCase(t) s.compareTo(t)never == to compare text; compareTo < 0 if it goes first
s.contains("x") s.startsWith("P") s.toUpperCase() s.trim()contains, starts with, upper case, trim
s.split(",") String.join("-", parts) s.replace("a", "b")split into an array, join, replace
StringBuilder sb = new StringBuilder(); sb.append(x).append("->"); sb.toString();build text in a loop

Arrays

int[] v = new int[5]; int[] w = {3, 1, 2}; v.lengthfixed size; length without brackets
Arrays.toString(v) Arrays.sort(v) Arrays.copyOf(v, 3) Arrays.fill(v, 0)java.util.Arrays class
Arrays.equals(a, b) Arrays.asList(1, 2)compare contents (not ==) / to a list
String[] r = new String[size]; int i = 0; for (Node n = first; n != null; n = n.next) r[i++] = n.value.name;turn a linked list into an array

Classes and objects

public class Queue { private int size; private static int total = 0; public Queue() { … } }private hidden, static belongs to the class, constructor without a type
public int getSize() { return size; }getter: read-only access
this.name = name;this tells the attribute from the parameter
public / protected / (paquete) / privatefrom most to least visible; protected: subclasses
@Override public String toString() { return …; }object text in println
obj == null a.equals(b) a == b== compares references (the same object?)

Inheritance and interfaces

class Child extends Base { Child(int a) { super(a); } }extends and super(…) on the first line
public abstract class Shape { abstract double area(); }abstract: it cannot be created with new
class Square implements Shape, Comparable<Square> { … }one parent class, several interfaces
public int compareTo(Player o) { return Integer.compare(o.points, points); }natural order (here, from most to fewest)
if (x instanceof Circle c) { … c.radius … }check the type and use it

Exceptions

throw new IllegalArgumentException("invalid quantity");throw (unchecked ones need no throws)
try { … } catch (NumberFormatException e) { e.getMessage(); } finally { … }catch; finally always runs
class BalanceException extends Exception { … }checked: it forces throws or try
NullPointerException ArrayIndexOutOfBoundsException ClassCastExceptionthe three most typical in structures

Collections (outside the structures)

List<Integer> l = new ArrayList<>(); l.add(3); l.get(0); l.size();dynamic list (not allowed to store the exam data)
Map<String, Integer> m = new HashMap<>(); m.getOrDefault(k, 0);dictionary; TreeMap sorts it by key
for (Map.Entry<String, Integer> e : m.entrySet()) e.getKey();walk a map
Scanner sc = new Scanner(System.in); sc.nextInt(); sc.nextLine();read from the keyboard (watch the newline after nextInt)

Linked lists in Java

for (Node n = first; n != null; n = n.next) { … }walk it
Node n = new Node(x); if (first == null) first = n; else last.next = n; last = n;append at the end
Node prev = null, n = first; while (n != null && !n.value.equals(x)) { prev = n; n = n.next; }search keeping the previous one (to be able to remove)
n.prev.next = n.next; n.next.prev = n.prev;doubly linked: two links per change
Casos: vacía, un nodo, primero, último, `last` y `null`the tryout file is not marked: use it

Before you hand in, ask yourself:

  1. Have you tried the empty list, one element, the first and the last one (and adding afterwards)?
  2. Do all the methods have the exact name, parameters and return of the statement?
  3. Do you store the data only in nodes (no Python lists or Java collections)?
  4. Do you have free evaluations left, or does the next one already subtract?

Summary

  • Each FP2 practical exam is a class to complete in VPL, with a tryout file that is not marked and some given classes.
  • The mark is the tests’ mark: the sum of the weights of the ones you pass, out of 10, with a comment per failure.
  • The first 10 evaluations are free; from the 11th, each one subtracts 0.1.
  • In linked lists, the exam is decided in removing: first, the previous node’s next and last.
  • Write the whole skeleton before anything else: in Java, without it no test compiles.
ExamTimeKey
1 (Python)75 minEncapsulation, properties and class attributes
2 (Python)75 minSingly and doubly linked lists
3 (Java)75 minLinked lists with null and equals
Resit120 minOne of each, 5 + 5

You have every mock exam of the degree in Exams and mock exams. Good luck in the VPL!

Keep goingAll Python articles

Did this article help you? Here is how you can support SergioLearns →