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.
Table of Contents
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.
Sports center court booking
A sports center wants to manage its members’ court bookings. Complete the Booking class in the booking.py module: a member creates a booking, adds courts by the hour while it is pending and finally confirms it.
The Courts class (module courts.py, already written) gives the information of each court: its class method Courts.info(code) returns a tuple (name, price_per_hour) or None if that court does not exist.
General notes
- Add the instance and class attributes you need, hidden (encapsulated): none of them can be public.
- No checks are required beyond the ones listed.
Initialiser
- It receives, in this order,
booking_id(str) andmember(str). The booking starts pending and with no courts.
Properties (all read-only)
idandmember: the initialiser data.confirmed:Trueonce it has been confirmed.total: sum of price per hour × hours of every court (float).
Methods
add(code, hours=1): adds hours of a court. If the court was already in the booking, it adds the hours to the ones it had. It raisesValueErrorifhoursis not anintor is less than 1, if the booking is confirmed or if the court does not exist.remove(code): removes the court from the booking and returns how many hours it had.ValueErrorif the booking is confirmed or that court is not in it.lines(): list of(code, hours)tuples in the order in which each court was first added.confirm(): confirms the booking.ValueErrorif it was already confirmed or it has no courts. If it works, it counts towards the class total.- Class method
total_confirmed(): number of bookings confirmed successfully. __str__: exactlyBooking <id> for <member>: <n> courts, <h> h - <Pending|Confirmed> - Total <total>€, withn= number of different courts,h= total hours and the total with 2 decimals.
Example
b = Booking("R-7", "Ana")
b.add("PADEL-1", 2)
b.add("TENNIS-1")
b.add("PADEL-1")
print(b) # Booking R-7 for Ana: 2 courts, 4 h - Pending - Total 45.50€Solution
booking.py
from courts import Courts
class Booking:
"""A member's court booking: hours are added while it is pending and then it is confirmed."""
__confirmed = 0 # class attribute (hidden): bookings confirmed successfully
def __init__(self, booking_id, member):
self.__id = booking_id
self.__member = member
self.__confirmed_flag = False
self.__hours = {} # court code -> hours (a dict keeps insertion order)
@property
def id(self):
return self.__id
@property
def member(self):
return self.__member
@property
def confirmed(self):
return self.__confirmed_flag
@property
def total(self):
# price per hour of each court (Courts.info(c)[1]) times its hours
return sum(Courts.info(c)[1] * h for c, h in self.__hours.items())
def add(self, code, hours=1):
# type(...) is not int: neither 1.5 nor True (bool is an int) pass as hours
if type(hours) is not int or hours < 1:
raise ValueError("invalid hours")
if self.__confirmed_flag:
raise ValueError("the booking is already confirmed")
if Courts.info(code) is None:
raise ValueError("court not available")
self.__hours[code] = self.__hours.get(code, 0) + hours # if it was already there, add up
def remove(self, code):
if self.__confirmed_flag:
raise ValueError("the booking is already confirmed")
if code not in self.__hours:
raise ValueError("that court is not in the booking")
return self.__hours.pop(code) # pop deletes the key and returns its hours
def lines(self):
return list(self.__hours.items())
def confirm(self):
if self.__confirmed_flag:
raise ValueError("the booking is already confirmed")
if not self.__hours:
raise ValueError("the booking is empty")
self.__confirmed_flag = True
Booking.__confirmed += 1 # counted in the class, not in the object
@classmethod
def total_confirmed(cls):
return cls.__confirmed
def __str__(self):
state = "Confirmed" if self.__confirmed_flag else "Pending"
n, hours = len(self.__hours), sum(self.__hours.values())
return f"Booking {self.__id} for {self.__member}: {n} courts, {hours} h - {state} - Total {self.total:.2f}€"A dict of code → hours stores the courts without repeating them and in arrival order (dicts keep insertion order since Python 3.7), so add adds up with get(code, 0) and lines() comes from items(). The confirmed counter is a class attribute: it is incremented through Booking.__confirmed (not self, which would create a new attribute in the object). type(hours) is not int also rejects True and 1.5.
Shop turn queue
At a shop counter customers take a turn and are served in order of arrival. Complete the TurnQueue class in the turns.py module, which stores the turns in a singly linked list with the attributes first and last.
You are given the Ticket class (in the same module; public attributes number, name and priority, and str = #<number> <name> with a * if it has priority), the inner Node class and the ContainerBase class (module containerbase.py), which TurnQueue inherits from and whose __str__ draws the list.
You cannot use Python lists (or other collections) to store the turns.
Methods and properties
take(name, priority=False): creates aTicketwith the next number of this queue (1, 2, 3…; a cancelled number is not reused), adds it at the end and returns its number.serve(): removes and returns the first turn, and adds one to the served count. If the queue is empty it returnsNone(and adds nothing).- Read-only property
served: turns served since the queue was created. __len__: turns waiting.cancel(number): removes the turn with that number from the queue, wherever it is, and returnsTrue; if it is not there,False. Watchlastif you remove the last one.split_priority(): creates and returns a new queue with the priority turns, which leave the original one. Both queues keep their relative order; the served count of the original does not change and the new one starts withservedat 0.
Example
q = TurnQueue()
q.take("Ana"); q.take("Luis", True); q.take("Eva")
print(q) # ➡[#1 Ana]->[#2 Luis*]->[#3 Eva]⬅->None
print(q.serve()) # #1 AnaSolution
turns.py
from containerbase import ContainerBase
class Ticket:
"""A turn (already written: do not change it)."""
def __init__(self, number, name, priority=False):
self.number = number
self.name = name
self.priority = priority
def __str__(self):
return f"#{self.number} {self.name}" + ("*" if self.priority else "")
class TurnQueue(ContainerBase):
class Node:
def __init__(self, value, next=None):
self.value = value # the Ticket
self.next = next # the next node
def __init__(self):
self.first = None
self.last = None
self.__count = 0 # nodes in the list (so len() does not walk it)
self.__next_number = 1 # the number the next take() gives
self.__served = 0
def __append(self, ticket):
# append at the end: O(1) thanks to last
node = TurnQueue.Node(ticket)
if self.first is None:
self.first = node
else:
self.last.next = node
self.last = node
self.__count += 1
def take(self, name, priority=False):
ticket = Ticket(self.__next_number, name, priority)
self.__next_number += 1 # never reused, even if cancelled
self.__append(ticket)
return ticket.number
def serve(self):
if self.first is None:
return None
ticket = self.first.value
self.first = self.first.next
if self.first is None: # it is now empty: last to None too
self.last = None
self.__count -= 1
self.__served += 1
return ticket
@property
def served(self):
return self.__served
def __len__(self):
return self.__count
def cancel(self, number):
prev, node = None, self.first
while node is not None and node.value.number != number:
prev, node = node, node.next
if node is None:
return False
if prev is None: # it was the first one
self.first = node.next
else:
prev.next = node.next
if node is self.last: # it was the last one: last moves back
self.last = prev
self.__count -= 1
return True
def split_priority(self):
vip = TurnQueue()
vip.__next_number = self.__next_number
prev, node = None, self.first
while node is not None:
nxt = node.next
if node.value.priority:
# unhook the node from this queue…
if prev is None:
self.first = nxt
else:
prev.next = nxt
if node is self.last:
self.last = prev
self.__count -= 1
vip.__append(node.value) # …and append its turn to the new one
else:
prev = node
node = nxt
return vipEverything is about unhooking a node with two pointers (prev and node): if prev is None, first moves; if the node was last, last becomes prev. Keeping the count in an attribute makes len() instant, and the next turn number is a separate counter so a cancelled one is never repeated. split_priority reuses the same walk and each priority turn is appended to the end of the new queue.
Warehouse box stack
In a warehouse boxes are stacked: the last one in is the first one that can be taken out. Write the BoxStack class in Java, which stores the boxes in a singly linked list where first is the top of the stack.
BoxStack extends ContainerBase (already written), which provides the first attribute and a toString() that draws the stack from the top: ➡[A (3.5 kg)]->[B (2.0 kg)]->null. You are also given Box (public attributes label and kg) and Node (with value and next; its constructor receives a Box). You can add helper attributes and methods.
You cannot use Java arrays or collections (ArrayList, LinkedList, Stack…) to store the boxes.
Public methods
push(Box box): puts the box on top.pop(): removes and returns the box on top;nullif the stack is empty.peek(): returns the box on top without removing it;nullif it is empty.getSize(): number of boxes.getTotalKg(): sum of the kilos (double).heaviest(): the heaviest box (if there is a tie, the one closest to the top);nullif it is empty.popUntil(String label): if there is a box with that label, it takes boxes off the top up to and including it and returns how many it took off; if there is none, it takes nothing off and returns 0.
Example
BoxStack s = new BoxStack();
s.push(new Box("A", 3.5));
s.push(new Box("B", 2.0));
System.out.println(s); // ➡[B (2.0 kg)]->[A (3.5 kg)]->nullSolution
BoxStack.java
public class BoxStack extends ContainerBase {
private int size; // the count is kept to avoid walking
public void push(Box box) {
Node n = new Node(box);
n.next = first; // the new one points to the old top…
first = n; // …and becomes the top
size++;
}
public Box pop() {
if (first == null) {
return null;
}
Box b = first.value;
first = first.next;
size--;
return b;
}
public Box peek() {
return first == null ? null : first.value;
}
public int getSize() {
return size;
}
public double getTotalKg() {
double total = 0;
for (Node n = first; n != null; n = n.next) {
total += n.value.kg;
}
return total;
}
public Box heaviest() {
Box best = null;
for (Node n = first; n != null; n = n.next) {
if (best == null || n.value.kg > best.kg) { // > not >=: in a tie the one closest to the top wins
best = n.value;
}
}
return best;
}
public int popUntil(String label) {
boolean found = false;
for (Node n = first; n != null && !found; n = n.next) {
found = n.value.label.equals(label); // equals, never == with String
}
if (!found) {
return 0; // if it is not there, nothing is taken off
}
int count = 0;
Box b;
do {
b = pop();
count++;
} while (!b.label.equals(label));
return count;
}
}A linked stack does not need last: push and pop always work on first, in O(1). popUntil first checks that the label is there (otherwise it must not touch the stack) and then reuses pop() until it takes it off; labels are compared with equals, because == compares references and fails with a String created with new.
Temperature log
A weather station stores the temperatures (integers) it measures. Complete the TempLog class in the temps.py module, which stores them in a singly linked list with the attribute first, and write the inheritance from ContainerBase yourself (module containerbase.py, already written, which shows |->21->19->None). You are given the inner Node class. You cannot use Python lists to store the temperatures.
Methods and properties
add_first(value)andadd_last(value): add at the start and at the end.add_at(value, pos): inserts at positionpos(starting at 0) and shifts the others. Ifposis less than 0 it is added at the start; if it is greater than or equal to the size, at the end.sizeproperty, read and write: reading returns how many there are. Writing, if the value is between 0 and the size minus 1, trims the list to that size (deletes the positions equal or greater); with any other value it does nothing.__iter__, as a generator: walks from start to end.ends_with(values): receives a Python list and returnsTrueif the last temperatures match, in order, the ones in that list (the empty list always matches).
Example
t = TempLog() t.add_last(21); t.add_last(19); t.add_first(23) print(t) # |->23->21->19->None
Solution
temps.py
from containerbase import ContainerBase
class TempLog(ContainerBase):
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
def __init__(self):
self.first = None
self.__size = 0
def add_first(self, value):
self.first = TempLog.Node(value, self.first)
self.__size += 1
def add_last(self, value):
if self.first is None:
self.add_first(value)
return
node = self.first
while node.next is not None: # no last: you have to reach the end
node = node.next
node.next = TempLog.Node(value)
self.__size += 1
def add_at(self, value, pos):
if pos <= 0:
self.add_first(value)
elif pos >= self.__size:
self.add_last(value)
else:
node = self.first
for _ in range(pos - 1): # stop at the node BEFORE pos
node = node.next
node.next = TempLog.Node(value, node.next)
self.__size += 1
@property
def size(self):
return self.__size
@size.setter
def size(self, new):
if not (0 <= new < self.__size):
return # out of range: it does nothing
if new == 0:
self.first = None
else:
node = self.first
for _ in range(new - 1):
node = node.next
node.next = None # cuts what comes after
self.__size = new
def __iter__(self):
node = self.first
while node is not None:
yield node.value
node = node.next
def ends_with(self, values):
if len(values) > self.__size:
return False
node = self.first
for _ in range(self.__size - len(values)): # skip to where the tail starts
node = node.next
for v in values:
if node.value != v:
return False
node = node.next
return TrueWithout last, add_last has to walk to the end, and add_at stops at the node before pos (hence pos - 1). The size setter cuts by setting next = None on node new - 1; the 0 case goes separately. ends_with skips size - len(values) nodes and compares from there.
Supermarket checkout queue
Write the CheckoutQueue class in Java: the queue of a supermarket checkout, stored in a singly linked list with first (the next one to pay) and last. It extends ContainerBase (already written: attributes first and last and a toString() like ➡[Ana(3)]->[Luis(12)]⬅->null). You are given Customer (public attributes name and items) and Node. You cannot use arrays or collections.
Public methods
arrive(Customer c): the customer joins at the end.serve(): removes and returns the first one;nullif nobody is there.getCustomer(int pos): the customer at positionpos(from 0) without removing them;nullif the position is not valid.getPendingItems(): total items of the people waiting.getSize(): number of customers.expressLane(int maxItems): opens an express checkout: it creates and returns a new queue with the customers carrying at mostmaxItemsitems, who leave this one. Both queues keep their order. Watchlastin both.
Example
CheckoutQueue q = new CheckoutQueue();
q.arrive(new Customer("Ana", 3));
q.arrive(new Customer("Luis", 12));
System.out.println(q); // ➡[Ana(3)]->[Luis(12)]⬅->nullSolution
CheckoutQueue.java
public class CheckoutQueue extends ContainerBase {
private int size;
public void arrive(Customer c) {
Node n = new Node(c);
if (first == null) {
first = n;
} else {
last.next = n;
}
last = n;
size++;
}
public Customer serve() {
if (first == null) {
return null;
}
Customer c = first.value;
first = first.next;
if (first == null) {
last = null; // the queue is now empty
}
size--;
return c;
}
public Customer getCustomer(int pos) {
if (pos < 0 || pos >= size) {
return null;
}
Node n = first;
for (int i = 0; i < pos; i++) {
n = n.next;
}
return n.value;
}
public int getPendingItems() {
int total = 0;
for (Node n = first; n != null; n = n.next) {
total += n.value.items;
}
return total;
}
public int getSize() {
return size;
}
public CheckoutQueue expressLane(int maxItems) {
CheckoutQueue express = new CheckoutQueue();
Node prev = null, n = first;
while (n != null) {
Node next = n.next;
if (n.value.items <= maxItems) {
if (prev == null) {
first = next; // the first one leaves
} else {
prev.next = next;
}
if (n == last) {
last = prev; // the last one leaves
}
size--;
express.arrive(n.value);
} else {
prev = n;
}
n = next;
}
return express;
}
}It is the Java version of «splitting» a list: a walk with prev and n, saving next before touching anything; each node that matches is unhooked (moving first or last if needed) and its customer goes to the new queue with arrive, which already keeps the order.
Hiking routes
A hiking club publishes its routes on a website: each route is built from trail sections and is only shown when it is ready. Complete the Route class in route.py.
The Trails class (module trails.py, already written) has the class method Trails.data(code), which returns a tuple (name, km, climb) (km is a float and climb, in metres, an int) or None if the section does not exist.
General notes
- Hidden instance and class attributes; no checks beyond the ones listed.
Initialiser
- It receives
nameandguide(str). The route starts hidden and with no sections.
Properties
name,guide(read-only).km(read-only): sum of the km of the sections.climb(read-only): sum of the climbs.visible(read and write): writing only acceptsTrueorFalse(otherwiseTypeError) and does not allowTrueif the route has fewer than 2 sections (ValueError).
Methods
add(code): adds the section at the end.ValueErrorif the section does not exist or is already in the route.sections(): list with the names of the sections, in order.duration(): estimated minutes,km × 15 + climb / 10, rounded to an integer withround.__len__: number of sections.- Class method
visible_routes(): how many routes are visible right now (if a route is hidden again, it stops counting). __str__: exactlyRoute <name> (guide <guide>): <n> sections, <km> km, +<climb> m - <Visible|Hidden>with the km to 1 decimal.
Example
r = Route("Summit", "Luis")
r.add("S01")
r.add("S02")
r.visible = True
print(r) # Route Summit (guide Luis): 2 sections, 6.0 km, +410 m - VisibleSolution
route.py
from trails import Trails
class Route:
"""Hiking route made of sections; it is only shown (visible) when it has at least 2."""
__visible_count = 0 # class attribute: routes visible right now
def __init__(self, name, guide):
self.__name = name
self.__guide = guide
self.__codes = [] # codes of the sections, in order (lists are allowed in exam 1)
self.__visible = False
@property
def name(self):
return self.__name
@property
def guide(self):
return self.__guide
@property
def km(self):
return sum(Trails.data(c)[1] for c in self.__codes)
@property
def climb(self):
return sum(Trails.data(c)[2] for c in self.__codes)
@property
def visible(self):
return self.__visible
@visible.setter
def visible(self, value):
if type(value) is not bool:
raise TypeError("visible only accepts True or False")
if value and len(self.__codes) < 2:
raise ValueError("a visible route needs at least 2 sections")
if value != self.__visible: # it only counts if the state changes
Route.__visible_count += 1 if value else -1
self.__visible = value
def add(self, code):
if Trails.data(code) is None:
raise ValueError("unknown section")
if code in self.__codes:
raise ValueError("that section is already in the route")
self.__codes.append(code)
def sections(self):
return [Trails.data(c)[0] for c in self.__codes]
def duration(self):
return round(self.km * 15 + self.climb / 10)
def __len__(self):
return len(self.__codes)
@classmethod
def visible_routes(cls):
return cls.__visible_count
def __str__(self):
state = "Visible" if self.__visible else "Hidden"
return (f"Route {self.__name} (guide {self.__guide}): {len(self)} sections, "
f"{self.km:.1f} km, +{self.climb} m - {state}")The key is the visible setter: it checks the type with type(value) is not bool, requires 2 sections to set it to True and only touches the class counter if the state changes (setting True twice must not count twice). km and climb are computed when asked for, so they never get out of sync with the sections.
Undo and redo in an editor
A drawing editor stores the user’s actions so they can be undone and redone. Complete the UndoHistory class in the editor.py module, which stores the actions (strings) in a doubly linked list with the attributes first and current.
current points to the node of the last action done; if it is None, the editor is in its initial state (nothing is done, although the list may hold actions that can be redone). You are given the inner Node class (with value, prev and next) and ContainerBase (module containerbase.py), whose __str__ marks current with {*…*}. You cannot use Python lists.
Methods and properties
do(action): does a new action: it deletes everything aftercurrent(ifcurrentisNone, the whole list), appends the action after it and makes itcurrent.undo(): undoes the current action:currentmoves to the previous one and it returns the undone action. If nothing is done, it returnsNone.redo(): redoes the next action (ifcurrentisNone, the first one in the list), makes itcurrentand returns it; if there is nothing to redo,None.- Read-only property
current_action: the action atcurrentorNone. __len__: number of actions in the list (including the ones that can be redone).count(action): how many times that action appears in the list.
Example
h = UndoHistory()
h.do("line"); h.do("circle"); h.do("text")
print(h.undo()) # text
print(h) # ->[line]<->{*circle*}<->[text]->NoneSolution
editor.py
from containerbase import ContainerBase
class UndoHistory(ContainerBase):
class Node:
def __init__(self, value, prev=None, next=None):
self.value = value # the action (str)
self.prev = prev
self.next = next
def __init__(self):
self.first = None
self.current = None # node of the last action done (None = initial state)
def do(self, action):
node = UndoHistory.Node(action, self.current)
if self.current is None:
# initial state: whatever was there is lost and the action becomes the first
self.first = node
else:
# cut what was after current and hook the new one
self.current.next = node
self.current = node
def undo(self):
if self.current is None:
return None
action = self.current.value
self.current = self.current.prev # it may end up as None: initial state
return action
def redo(self):
following = self.first if self.current is None else self.current.next
if following is None:
return None
self.current = following
return following.value
@property
def current_action(self):
return None if self.current is None else self.current.value
def __len__(self):
n, node = 0, self.first
while node is not None:
n, node = n + 1, node.next
return n
def count(self, action):
n, node = 0, self.first
while node is not None:
if node.value == action:
n += 1
node = node.next
return nThe key idea is that do does not need to delete node by node: it is enough for current.next to point to the new one (or first, if current is None), and whatever was ahead is unhooked. undo and redo only move current: the initial state is current = None, and from there redo starts at first.
Tournament leaderboard
A video game tournament wants its leaderboard always sorted. Write the Leaderboard class in Java: it stores the players in a singly linked list, sorted from most to fewest points; in a tie, whoever reached that score first goes in front.
Leaderboard extends ContainerBase (already written: attribute first and a toString() like ➡[Ana:30]->[Luis:20]->null). You are given Player (public attributes name and points) and Node (with value and next). You cannot use arrays or collections to store the players (an array is returned in top).
Public methods
add(Player p): inserts the player in their place (after the ones with the same points).getSize(): number of players.getPosition(String name): position of the player starting at 1; -1 if they are not there.remove(String name): removes the player;trueif they were there,falseif not.addPoints(String name, int points): adds the points to the player and re-places them in the leaderboard (after the ones that already had that score);falseif they are not there.top(int n): aPlayer[]array with the firstn(or all of them, if there are fewer; empty ifn <= 0).
Example
Leaderboard lb = new Leaderboard();
lb.add(new Player("Ana", 20));
lb.add(new Player("Luis", 35));
System.out.println(lb); // ➡[Luis:35]->[Ana:20]->nullSolution
Leaderboard.java
public class Leaderboard extends ContainerBase {
private int size;
public void add(Player p) {
Node n = new Node(p);
// it goes before the first one with FEWER points (in a tie, after)
if (first == null || p.points > first.value.points) {
n.next = first;
first = n;
} else {
Node prev = first;
while (prev.next != null && prev.next.value.points >= p.points) {
prev = prev.next;
}
n.next = prev.next;
prev.next = n;
}
size++;
}
public int getSize() {
return size;
}
public int getPosition(String name) {
int pos = 1;
for (Node n = first; n != null; n = n.next, pos++) {
if (n.value.name.equals(name)) {
return pos;
}
}
return -1;
}
// unhooks the player's node and returns the player (or null)
private Player unhook(String name) {
Node prev = null, n = first;
while (n != null && !n.value.name.equals(name)) {
prev = n;
n = n.next;
}
if (n == null) {
return null;
}
if (prev == null) {
first = n.next;
} else {
prev.next = n.next;
}
size--;
return n.value;
}
public boolean remove(String name) {
return unhook(name) != null;
}
public boolean addPoints(String name, int points) {
Player p = unhook(name); // it is taken out…
if (p == null) {
return false;
}
p.points += points;
add(p); // …and put back in its new place
return true;
}
public Player[] top(int n) {
int k = Math.max(0, Math.min(n, size));
Player[] result = new Player[k];
Node node = first;
for (int i = 0; i < k; i++) {
result[i] = node.value;
node = node.next;
}
return result;
}
}Sorted insertion looks for the last node with points ≥ the new one (so the tie goes after) and handles the go-first case separately. addPoints is the neat idea: instead of moving nodes by hand, it unhooks the player with the private unhook method, adds the points and puts them back with add, which already knows where they go.
Sticker album
Complete the StickerAlbum class in the album.py module: an album with the names of the stickers (strings) without repeats and sorted alphabetically, stored in a singly linked list with the attribute first. Write the inheritance from ContainerBase yourself (module containerbase.py, already written, which shows |->Ana->Luis->None). You are given the inner Node class. You cannot use Python lists to store the stickers.
Methods
add(name): sticks the sticker in its place (alphabetical order with<between strings). If it was already there, it does not repeat it. It returnsTrueif it added it andFalseif it was already there.remove(name): removes it;Trueif it was there,Falseif not.__contains__(name):Trueif it is there (since it is sorted, you can stop early).__len__: number of stickers.__iter__, as a generator: walks them in order.missing_from(other): returns a new album with the stickersotherhas and this one does not. Neither of them changes.
Example
a = StickerAlbum()
for n in ("Pedri", "Alexia", "Pedri"):
a.add(n)
print(a) # |->Alexia->Pedri->NoneSolution
album.py
from containerbase import ContainerBase
class StickerAlbum(ContainerBase):
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
def __init__(self):
self.first = None
self.__count = 0
def add(self, name):
if self.first is None or name < self.first.value:
self.first = StickerAlbum.Node(name, self.first)
elif name == self.first.value:
return False
else:
node = self.first
while node.next is not None and node.next.value < name:
node = node.next
if node.next is not None and node.next.value == name:
return False # already there: no repeats
node.next = StickerAlbum.Node(name, node.next)
self.__count += 1
return True
def remove(self, name):
prev, node = None, self.first
while node is not None and node.value < name:
prev, node = node, node.next
if node is None or node.value != name:
return False
if prev is None:
self.first = node.next
else:
prev.next = node.next
self.__count -= 1
return True
def __contains__(self, name):
node = self.first
while node is not None and node.value <= name:
if node.value == name:
return True
node = node.next
return False
def __len__(self):
return self.__count
def __iter__(self):
node = self.first
while node is not None:
yield node.value
node = node.next
def missing_from(self, other):
result = StickerAlbum()
for name in other:
if name not in self:
result.add(name)
return resultIt is the usual sorted insertion with one more check: before hooking you look whether the next one is equal (and the first-node case goes separately). Since the list is sorted, remove and in stop as soon as they see a larger name. missing_from reuses in and add, so the result comes out sorted by itself.
To-do list
Write the TaskList class in Java: a to-do list stored in a singly linked list with first and last, which extends ContainerBase (already written: toString() like ➡[Study 30min]->[Run 45min ✔]⬅->null). You are given Task (public attributes title, minutes and done, the latter false when created) and Node. You cannot use collections or store the tasks in an array (an array is returned in titles).
Public methods
add(Task t): adds at the end.getTask(int pos): the task at positionpos(from 0);nullif it is not valid.complete(int pos): marks the task at that position as done;trueif it did andfalseif the position is not valid or it was already done.getPendingMinutes(): minutes of the tasks not done.removeDone(): deletes every done task from the list and returns how many it deleted. Watchfirstandlast.titles(): aString[]with the titles in order.getSize(): number of tasks.
Example
TaskList l = new TaskList();
l.add(new Task("Study", 30));
l.add(new Task("Run", 45));
l.complete(1);
System.out.println(l); // ➡[Study 30min]->[Run 45min ✔]⬅->nullSolution
TaskList.java
public class TaskList extends ContainerBase {
private int size;
public void add(Task t) {
Node n = new Node(t);
if (first == null) {
first = n;
} else {
last.next = n;
}
last = n;
size++;
}
private Node nodeAt(int pos) {
if (pos < 0 || pos >= size) {
return null; // invalid position
}
Node n = first;
for (int i = 0; i < pos; i++) {
n = n.next;
}
return n;
}
public Task getTask(int pos) {
Node n = nodeAt(pos);
return n == null ? null : n.value;
}
public boolean complete(int pos) {
Node n = nodeAt(pos);
if (n == null || n.value.done) {
return false;
}
n.value.done = true;
return true;
}
public int getPendingMinutes() {
int total = 0;
for (Node n = first; n != null; n = n.next) {
if (!n.value.done) {
total += n.value.minutes;
}
}
return total;
}
public int removeDone() {
int removed = 0;
Node prev = null, n = first;
while (n != null) {
if (n.value.done) {
if (prev == null) {
first = n.next;
} else {
prev.next = n.next;
}
if (n == last) {
last = prev;
}
removed++;
} else {
prev = n; // prev only moves on if the node stays
}
n = n.next;
}
size -= removed;
return removed;
}
public String[] titles() {
String[] result = new String[size];
int i = 0;
for (Node n = first; n != null; n = n.next) {
result[i++] = n.value.title;
}
return result;
}
public int getSize() {
return size;
}
}The private method nodeAt(pos) holds the position check, and getTask and complete use it. In removeDone the detail is that prev only moves on when the node stays: if it always moved, deleting two tasks in a row would let the second one slip through.
Bike workshop quotes
A bike workshop prepares parts quotes for its customers. Complete the Quote class in quote.py.
The Parts class (module parts.py, already written) has the class method Parts.data(ref), which returns a tuple (name, price, vat) (price without VAT in euros, vat as a percentage) or None if the reference does not exist. Careful: not every part has the same VAT.
General notes
- Hidden attributes; no checks beyond the ones listed.
Initialiser
- It receives
numberandcustomer(str). It starts pending and with no parts.
Properties (read-only)
number,customer,accepted(bool).base: sum of price × units.vat: sum of price × units × vat / 100 of each part.total:base + vat.
Methods
add(ref, units=1): adds units of a part (if it was already there, they add up).ValueErrorifunitsis not anintor is less than 1, if the quote is accepted or if the reference does not exist.remove(ref, units=1): removes units; if the part reaches 0, it disappears from the quote.ValueErrorif it is accepted, if the part is not there, ifunitsis not valid or if you try to remove more than there are.units(ref): units of that part (0 if it is not there).accept():ValueErrorif it was already accepted or it has no parts; if it works, it counts for the class.- Class method
accepted_count(): quotes accepted successfully. __len__: number of different parts.__str__: exactlyQuote <number> for <customer>: <n> parts - <Pending|Accepted> - Total <total>€(total with 2 decimals).
Example
q = Quote("P-14", "Marta")
q.add("CHAIN-11")
q.add("MAP-GC", 2)
print(q) # Quote P-14 for Marta: 2 parts - Pending - Total 52.29€Solution
quote.py
from parts import Parts
class Quote:
"""Parts quote: it changes while pending and is accepted once."""
__accepted = 0 # class attribute: quotes accepted
def __init__(self, number, customer):
self.__number = number
self.__customer = customer
self.__accepted_flag = False
self.__lines = {} # reference -> units
@property
def number(self):
return self.__number
@property
def customer(self):
return self.__customer
@property
def accepted(self):
return self.__accepted_flag
@property
def base(self):
return sum(Parts.data(r)[1] * u for r, u in self.__lines.items())
@property
def vat(self):
# each part with its own VAT: applying 21 % to the total is wrong
return sum(Parts.data(r)[1] * u * Parts.data(r)[2] / 100 for r, u in self.__lines.items())
@property
def total(self):
return self.base + self.vat
@staticmethod
def __check(units):
if type(units) is not int or units < 1:
raise ValueError("invalid units")
def add(self, ref, units=1):
Quote.__check(units)
if self.__accepted_flag:
raise ValueError("the quote is already accepted")
if Parts.data(ref) is None:
raise ValueError("unknown reference")
self.__lines[ref] = self.__lines.get(ref, 0) + units
def remove(self, ref, units=1):
if self.__accepted_flag:
raise ValueError("the quote is already accepted")
if ref not in self.__lines:
raise ValueError("that part is not in the quote")
Quote.__check(units)
if units > self.__lines[ref]:
raise ValueError("there are not that many units")
self.__lines[ref] -= units
if self.__lines[ref] == 0: # it reaches 0: the part disappears
del self.__lines[ref]
def units(self, ref):
return self.__lines.get(ref, 0)
def accept(self):
if self.__accepted_flag:
raise ValueError("the quote is already accepted")
if not self.__lines:
raise ValueError("the quote is empty")
self.__accepted_flag = True
Quote.__accepted += 1
@classmethod
def accepted_count(cls):
return cls.__accepted
def __len__(self):
return len(self.__lines)
def __str__(self):
state = "Accepted" if self.__accepted_flag else "Pending"
return f"Quote {self.__number} for {self.__customer}: {len(self)} parts - {state} - Total {self.total:.2f}€"Each part has its own VAT, so vat is added up part by part (maps are at 4 %): applying 21 % to the total gives a different figure. To avoid repeating the units check, a private static method (__check) does it in add and remove. When a part reaches 0 it is deleted from the dictionary, so len() and str() count correctly.
Sorted sequence of integers
We want a sequence of integers that is always sorted from smallest to largest. Complete the SortedInts class in the sortedints.py module, which stores the integers in a singly linked list with the attribute first, and write the inheritance from ContainerBase yourself (module containerbase.py, already written, whose __str__ shows |->1->3->None).
You are given the inner Node class. You cannot use Python lists to store the integers (you can to receive or return data where it says so).
Methods and properties
add(value): inserts the integer in its place so the sequence stays sorted. Repeated values are allowed: the new one goes after the equal ones.remove_all(value): deletes every occurrence ofvalueand returns how many it deleted.- Read-only property
size: number of integers. __contains__(value)(value in s): it only walks as far as needed: since it is sorted, as soon as it finds a larger number it knows it is not there.__iter__, as a generator: walks the sequence from start to end.count_between(low, high): how many integers are betweenlowandhigh, both included.merge(other): returns a newSortedIntswith the integers of both, sorted. Neither of them changes.
Example
s = SortedInts()
for n in (7, 2, 9, 2):
s.add(n)
print(s) # |->2->2->7->9->None
print(s.size) # 4Solution
sortedints.py
from containerbase import ContainerBase
class SortedInts(ContainerBase):
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
def __init__(self):
self.first = None
self.__size = 0
def add(self, value):
# the new one goes before the first LARGER node (with <= the equal ones stay in front)
if self.first is None or value < self.first.value:
self.first = SortedInts.Node(value, self.first)
else:
node = self.first
while node.next is not None and node.next.value <= value:
node = node.next
node.next = SortedInts.Node(value, node.next)
self.__size += 1
def remove_all(self, value):
removed = 0
while self.first is not None and self.first.value == value: # the ones at the start
self.first = self.first.next
removed += 1
node = self.first
while node is not None and node.next is not None:
if node.next.value == value:
node.next = node.next.next # without moving on: the next one may be another equal one
removed += 1
elif node.next.value > value:
break # sorted: there will be no more
else:
node = node.next
self.__size -= removed
return removed
@property
def size(self):
return self.__size
def __contains__(self, value):
node = self.first
while node is not None and node.value <= value:
if node.value == value:
return True
node = node.next
return False
def __iter__(self):
node = self.first
while node is not None:
yield node.value
node = node.next
def count_between(self, low, high):
n = 0
for v in self:
if v > high:
break
if v >= low:
n += 1
return n
def merge(self, other):
result = SortedInts()
for v in self:
result.add(v)
for v in other:
result.add(v)
return resultTo insert in order you look for the last node with a value ≤ the new one (so the equal ones stay in front) and hook it after it; the start case (empty first or a larger one) goes separately. In remove_all, when node.next is deleted you do not move on, because the next one may be another equal one; and since the sequence is sorted, as soon as a larger value appears you can stop.
Music player
A music player has a list of songs and a current song that can be moved forwards and backwards. Write the MusicPlayer class in Java with a doubly linked list.
MusicPlayer extends ContainerBase (already written), which provides the attributes first, last and current and a toString() that marks the current one with {*…*}: ->[A (200 s)]<->{*B (180 s)*}->null. You are given Song (public attributes title and seconds) and Node (with value, prev and next). You cannot use arrays or collections.
Public methods
add(Song s): adds the song at the end. If there was no current song, the new one becomes current.next()/previous(): move the current song to the next / previous one. They returntrueif it was possible andfalseif not (no current song, or no next / previous one).getCurrent(): the current song, ornull.removeCurrent(): removes the current song from the list and returns it (nullif there is none). The new current one is the next one; if there is no next one, the previous one; if the list becomes empty,null. Watchfirst,lastand both links.getTotalSeconds(): total length of the list.getSize(): number of songs.
Example
MusicPlayer p = new MusicPlayer();
p.add(new Song("A", 200));
p.add(new Song("B", 180));
p.next();
System.out.println(p); // ->[A (200 s)]<->{*B (180 s)*}->nullSolution
MusicPlayer.java
public class MusicPlayer extends ContainerBase {
private int size;
public void add(Song s) {
Node n = new Node(s);
if (first == null) {
first = n;
} else {
last.next = n; // the last one points to the new one…
n.prev = last; // …and the new one to the last one (both links)
}
last = n;
if (current == null) {
current = n;
}
size++;
}
public boolean next() {
if (current == null || current.next == null) {
return false;
}
current = current.next;
return true;
}
public boolean previous() {
if (current == null || current.prev == null) {
return false;
}
current = current.prev;
return true;
}
public Song getCurrent() {
return current == null ? null : current.value;
}
public Song removeCurrent() {
if (current == null) {
return null;
}
Node n = current;
if (n.prev == null) {
first = n.next; // it was the first one
} else {
n.prev.next = n.next;
}
if (n.next == null) {
last = n.prev; // it was the last one
} else {
n.next.prev = n.prev;
}
current = n.next != null ? n.next : n.prev; // the next one or, if there is none, the previous one
size--;
return n.value;
}
public int getTotalSeconds() {
int total = 0;
for (Node n = first; n != null; n = n.next) {
total += n.value.seconds;
}
return total;
}
public int getSize() {
return size;
}
}In a doubly linked list every change touches two links: when adding, last.next and n.prev; when removing, the next of the previous one (or first) and the prev of the next one (or last). removeCurrent picks the new current one with a ternary: the next one if it exists, otherwise the previous one, and null when none is left.
Freight train
Complete the Train class in the train.py module, which stores the wagons in a singly linked list with first (the locomotive is at the front) and last. Train inherits from ContainerBase (module containerbase.py, already written, which draws ➡[cereal 20t]->[gas 35t]⬅->None). The same module gives you Wagon (public attributes kind and tons) and the inner Node class. You cannot use Python lists to store the wagons.
Methods and properties
attach(wagon): hooks the wagon at the end.attach_front(wagon): at the front.detach_last(): unhooks and returns the last wagon;Noneif the train is empty.__len__: number of wagons.- Read-only property
total_tons: tons of all the wagons. wagons_of(kind): generator that yields the wagons of that kind, in order.split(pos): splits the train: returns a new train with the wagons from positionpos(from 0) to the end, which leave this one. Ifposis not a valid position, it returns an empty train and this one does not change.
Example
t = Train()
t.attach(Wagon("cereal", 20)); t.attach(Wagon("gas", 35))
print(t) # ➡[cereal 20t]->[gas 35t]⬅->NoneSolution
train.py
from containerbase import ContainerBase
class Wagon:
"""A wagon (already written: do not change it)."""
def __init__(self, kind, tons):
self.kind = kind
self.tons = tons
def __str__(self):
return f"{self.kind} {self.tons}t"
class Train(ContainerBase):
class Node:
def __init__(self, value, next=None):
self.value = value # the Wagon
self.next = next
def __init__(self):
self.first = None
self.last = None
self.__count = 0
def attach(self, wagon):
node = Train.Node(wagon)
if self.first is None:
self.first = node
else:
self.last.next = node
self.last = node
self.__count += 1
def attach_front(self, wagon):
self.first = Train.Node(wagon, self.first)
if self.last is None: # the train was empty
self.last = self.first
self.__count += 1
def detach_last(self):
if self.first is None:
return None
wagon = self.last.value
if self.first is self.last: # there was only one
self.first = self.last = None
else:
node = self.first
while node.next is not self.last: # singly linked: you have to find the second to last
node = node.next
node.next = None
self.last = node
self.__count -= 1
return wagon
def __len__(self):
return self.__count
@property
def total_tons(self):
total, node = 0, self.first
while node is not None:
total += node.value.tons
node = node.next
return total
def wagons_of(self, kind):
node = self.first
while node is not None:
if node.value.kind == kind:
yield node.value
node = node.next
def split(self, pos):
tail = Train()
if not (0 <= pos < self.__count):
return tail # invalid position: nothing changes
if pos == 0:
tail.first, tail.last = self.first, self.last
self.first = self.last = None
else:
node = self.first
for _ in range(pos - 1): # the wagon that stays last
node = node.next
tail.first, tail.last = node.next, self.last
node.next = None
self.last = node
tail.__count = self.__count - pos
self.__count = pos
return tailWith first and last, hooking at the end is O(1), but unhooking the last one is not: in a singly linked list you have to find the second to last. split cuts after node pos - 1: the new train keeps node.next and the old last, and the two counters are shared out (pos and the rest).
Warehouse inventory
Write the Inventory class in Java: the items of a warehouse stored in a singly linked list with first, sorted alphabetically by name and with no repeated names. It extends ContainerBase (already written: toString() like ➡[nails×200]->[screws×50]->null). You are given Item (public attributes name and quantity) and Node. You cannot use collections or store the items in an array (an array is returned in names).
Public methods
add(String name, int quantity): if the item is already there, it adds the quantity; if not, it inserts it in its place (compareToorder). Ifquantityis less than or equal to 0, it throwsIllegalArgumentException.take(String name, int quantity): takes that quantity out of the item; if it reaches 0, the item disappears from the list. It returnsfalse(changing nothing) if it is not there, ifquantity <= 0or if there is not that much; otherwisetrue.getQuantity(String name): the quantity of that item (0 if it is not there).getSize(): number of different items.names(): aString[]with the names, in order.
Example
Inventory inv = new Inventory();
inv.add("screws", 50);
inv.add("nails", 200);
System.out.println(inv); // ➡[nails×200]->[screws×50]->nullSolution
Inventory.java
public class Inventory extends ContainerBase {
private int size;
public void add(String name, int quantity) {
if (quantity <= 0) {
throw new IllegalArgumentException("invalid quantity");
}
Node prev = null, n = first;
while (n != null && n.value.name.compareTo(name) < 0) { // move on while the name is smaller
prev = n;
n = n.next;
}
if (n != null && n.value.name.equals(name)) {
n.value.quantity += quantity; // already there: add up
return;
}
Node created = new Node(new Item(name, quantity));
created.next = n;
if (prev == null) {
first = created;
} else {
prev.next = created;
}
size++;
}
public boolean take(String name, int quantity) {
Node prev = null, n = first;
while (n != null && !n.value.name.equals(name)) {
prev = n;
n = n.next;
}
if (n == null || quantity <= 0 || quantity > n.value.quantity) {
return false;
}
n.value.quantity -= quantity;
if (n.value.quantity == 0) { // it runs out: the item disappears
if (prev == null) {
first = n.next;
} else {
prev.next = n.next;
}
size--;
}
return true;
}
public int getQuantity(String name) {
for (Node n = first; n != null; n = n.next) {
if (n.value.name.equals(name)) {
return n.value.quantity;
}
}
return 0;
}
public int getSize() {
return size;
}
public String[] names() {
String[] result = new String[size];
int i = 0;
for (Node n = first; n != null; n = n.next) {
result[i++] = n.value.name;
}
return result;
}
}A single pass solves add: move on while the name is smaller (compareTo(name) < 0); when it stops, either the node has the same name (add up) or it is the insertion point (before n, after prev). In take everything is checked before subtracting, so the inventory is never left half-changed if the request is not valid.
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.
| Exam | Language | What it asks | Time | Marks |
|---|---|---|---|---|
| Exam 1 | Python | A class with hidden attributes, properties, class attributes and methods, exceptions and __str__ | 75 min | 10 |
| Exam 2 | Python | A linked list (singly or doubly linked) that inherits from ContainerBase | 75 min | 10 |
| Exam 3 | Java | A linked list that extends ContainerBase | 75 min | 10 |
| Resit | Python + Java | A linked list in each language | 120 min | 5 + 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 marked file (
booking.py,turns.py,BoxStack.java…): you complete it. The tests only look at this one. - The tryout file (
tryout.pyorTryout.java; in the real exam,prueba.pyorPruebas.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.ContainerBaseis the one that draws the list with➡,⬅and->when youprintit.
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
| Exam | What you have to master | Practice 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 ContainerBase | Linked lists in Python · Iterators and generators |
| Exam 3 (Java) | The same in Java: extends ContainerBase, null, equals, returning arrays, doubly linked lists | Classes and objects in Java · Inheritance in Java · Iterators in Java |
| Resit | One linked-list exercise in Python and another in Java | All 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):
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
- Read the whole statement and look at the given classes (the tabs with a padlock): which attributes they have and what they are called.
- Write the skeleton first: every method header and property with
pass(Python) or anyreturn(Java). In Java, if a method the tests use is missing, nothing compiles and you get a 0. - Run the tryout file (Run button or Ctrl+Enter) and compare with what the statement says.
- Evaluate and read the comments: each one tells you which case fails and what was expected.
- 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
javacand run with TeaVM, all in the browser. It has one difference that matters: aNullPointerExceptionor an index outside an array stop the programme (they cannot be caught withcatch) 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
whilethat 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
| Time | What to do |
|---|---|
| 0-10 min | Read the statement and the given classes; write the full skeleton |
| 10-25 min | The easy part: initialiser, add at the end, size, properties. Run |
| 25-55 min | The hard part: remove, search, split or re-place. Run with the odd cases |
| 55-70 min | Evaluate, read the comments and fix |
| 70-75 min | Check 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:
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
lastwhen 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 newnode.nextmay be another one that also has to go. - Public attributes in exam 1: the statement asks you to encapsulate; use
self.__xand properties. - Counting in the object what belongs to the class:
self.total += 1creates a new attribute in the object; the class counter is changed withClass.total. type(x) is intversusisinstance:isinstance(True, int)isTrue; if the statement says «an integer»,Trueshould 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:
- When
firstis created, Python Tutor draws four boxes chained by thenextarrow; the last one points toNone. - When
nodereaches the first 5, notice thatprevis still on the 3: the lineprev.next = node.nextmakes the 3’s arrow jump the 5. - On the next loop
nodeis on the second 5 andprevis still on the 3 (it did not move when removing): that is why the second 5 is also removed properly. - 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 bool7 // 2 → 3 7 % 2 → 1 2 ** 3 → 8floor division, remainder and powera, b = b, aswaps without a temporary variablef"{total:.2f}€" f"{n:>5}" f"{x!r}"f-string: 2 decimals, right-align, reprif 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 lists.find("ab") → -1 si no está s.count("a")find does not raise; index doess.startswith("P-") s.endswith(".py") "ab" in scheck start, end or containments[1:4] s[-1] s[::-1]slice, last character, reversedLists, tuples, dicts and sets
l.append(x) l.insert(0, x) l.pop() l.remove(x)append, insert at a position, pop, remove a valuesorted(l, key=len, reverse=True) l.sort()sorted returns another; sort changes the same onet = (1, 2) a, b = ttuple: immutable; it unpacksd.get(k, 0) d.items() d.pop(k) k in dget with a default; in looks at the keysd[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 filterFunctions
def f(a, b=1, *args, **kw): return a + bdefault and variable parameterslambda x: x[1]one-line function (for key=)sum(l) max(l) min(l, key=…) len(l) any(…) all(…)handy built-in functionsenumerate(l, 1) zip(a, b) reversed(l)index + value, pair up, walk backwardsClasses
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 clsOrder.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 objInheritance and exceptions
class Child(Base):
def __init__(self, a, b):
super().__init__(a)inherit and call the parent initialiserisinstance(x, Base) type(x) is intis it that class (or a child)? / exactly that type?raise ValueError("invalid quantity")raise an exception with a messagetry: …
except ValueError as e: print(e)
else: …
finally: …else if there was no error; finally alwaysclass BalanceError(Exception): passcustom exceptionLinked lists
nodo = self.first
while nodo is not None:
…
nodo = nodo.nextwalk it: do not forget to move onn = self.Node(x)
if self.first is None: self.first = n
else: self.last.next = n
self.last = nappend at the end with lastif 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 lastself.first = self.Node(x, self.first)add at the start in one lineCasos: vacía, un elemento, primero, últimoalways test them before EvaluateJava 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 String7 / 2 → 3 7 % 2 → 1 7 / 2.0 → 3.5between integers division is integer(int) 5.9 → 5 Integer.parseInt("42") String.valueOf(3)conversionsx = cond ? a : b; final int MAX = 10;ternary operator and constantSystem.out.println(x); System.out.printf("%.2f%n", d);print (with a newline) and formattedString.format("%5d|%-6s|%.1f", 42, "ab", 3.14)%d integer, %s text, %.1f decimal; – left-alignedControl flow
if (a > 0 && !empty) { … } else if (…) { … } else { … }&&, ||, !; always bracesfor (int i = 0; i < n; i++) { … } for (int x : array) { … }classic for and for-eachwhile (cond) { … } do { … } while (cond);do runs at least onceswitch (op) { case "+" -> r = a + b; default -> r = 0; }arrow switch (no break)break; continue; return x;exit, skip to the next iteration, returnStrings
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 firsts.contains("x") s.startsWith("P") s.toUpperCase() s.trim()contains, starts with, upper case, trims.split(",") String.join("-", parts) s.replace("a", "b")split into an array, join, replaceStringBuilder sb = new StringBuilder();
sb.append(x).append("->");
sb.toString();build text in a loopArrays
int[] v = new int[5]; int[] w = {3, 1, 2}; v.lengthfixed size; length without bracketsArrays.toString(v) Arrays.sort(v) Arrays.copyOf(v, 3) Arrays.fill(v, 0)java.util.Arrays classArrays.equals(a, b) Arrays.asList(1, 2)compare contents (not ==) / to a listString[] 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 arrayClasses 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 typepublic int getSize() { return size; }getter: read-only accessthis.name = name;this tells the attribute from the parameterpublic / protected / (paquete) / privatefrom most to least visible; protected: subclasses@Override
public String toString() { return …; }object text in printlnobj == 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 linepublic abstract class Shape { abstract double area(); }abstract: it cannot be created with newclass Square implements Shape, Comparable<Square> { … }one parent class, several interfacespublic 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 itExceptions
throw new IllegalArgumentException("invalid quantity");throw (unchecked ones need no throws)try { … } catch (NumberFormatException e) { e.getMessage(); } finally { … }catch; finally always runsclass BalanceException extends Exception { … }checked: it forces throws or tryNullPointerException ArrayIndexOutOfBoundsException ClassCastExceptionthe three most typical in structuresCollections (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 keyfor (Map.Entry<String, Integer> e : m.entrySet()) e.getKey();walk a mapScanner 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 itNode n = new Node(x);
if (first == null) first = n; else last.next = n;
last = n;append at the endNode 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 changeCasos: vacía, un nodo, primero, último, `last` y `null`the tryout file is not marked: use itBefore you hand in, ask yourself:
- Have you tried the empty list, one element, the first and the last one (and adding afterwards)?
- Do all the methods have the exact name, parameters and
returnof the statement? - Do you store the data only in nodes (no Python lists or Java collections)?
- 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’snextandlast. - Write the whole skeleton before anything else: in Java, without it no test compiles.
| Exam | Time | Key |
|---|---|---|
| 1 (Python) | 75 min | Encapsulation, properties and class attributes |
| 2 (Python) | 75 min | Singly and doubly linked lists |
| 3 (Java) | 75 min | Linked lists with null and equals |
| Resit | 120 min | One 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 articlesDid this article help you? Here is how you can support SergioLearns →



