FP1 practical mock exam — the continuous-assessment exams in Python, marked on the spot (rule of 8 included)
Has this ever happened to you: your function works with the example in the statement, you hand it in feeling calm and the VPL gives you a 6? It is almost always a case you did not try: a day without readings, an empty list, a tie. This mock exam recreates the FP1 practical exams inside the website: you choose the exam (the three continuous-assessment ones or the resit) and a version, and you program in the SergioLearns environment, which runs Python in your browser. As in the exam, you press Evaluate and get a mark out of 10 with a comment for each failing test.
There are 12 original exercises: three versions (A, B and C) of each exam, with the same format, the same difficulty and the same times as the real ones (35 minutes for the first and 40 for the others). Before the mock exam I explain what the exam is like; afterwards, how it is marked (with the famous «maximum mark: an 8»), how to split your time, the cases that fail most and the cheat sheets you could check.
Table of Contents
Take the mock exam
Choose the exam and the version (or «At random») and press Start: the exam takes up the whole window, with the statement on the left and the environment on the right. Complete the .py file, try it with Run and press 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.
Free seats at the cinema
A cinema stores each hall as a matrix: a list of rows, and each row a list of integers where 0 is a free seat and 1 a taken one. All rows have the same number of seats.
Exercise
In the cinema.py module, write a function called find_seats that receives a hall and an integer n (n ≥ 1) and returns a list of tuples (row, seat) with, for each row where a group of n people fits together, the first seat of the first gap of n free seats in a row. Rows and seats are numbered from 1, as at the box office. Rows without a gap do not appear and the order is the order of the rows. An empty hall ([]) gives [].
Note: you are advised to write a helper function that looks for the gap in one row; if you do not write it (and use it from find_seats), the maximum mark will be an 8.
Example
hall = [[1, 1, 0, 0, 0, 1, 0, 0],
[0, 1, 0, 1, 0, 1, 0, 1]]
find_seats(hall, 3) # [(1, 3)] (row 2 has no 3 free seats in a row)When you run cinema.py
The screen.py module (already written) draws the hall. With the solution, the if __name__ == "__main__": at the end prints:
1 X X · · · X · · 2 · X · X · X · X 3 · · · · X X X X 4 X X X X X · · · [(1, 3), (3, 1), (4, 6)]
Solution
cinema.py
from screen import draw_hall
def first_gap(row, n):
# Column (from 0) where n free seats in a row start, or -1 if there are none.
in_a_row = 0 # free seats in a row so far
for col in range(len(row)):
if row[col] == 0:
in_a_row += 1
if in_a_row == n: # the gap ends here: it started n - 1 columns before
return col - n + 1
else:
in_a_row = 0 # a taken seat breaks the run
return -1
def find_seats(hall, n):
result = []
for i in range(len(hall)):
col = first_gap(hall[i], n)
if col != -1:
result.append((i + 1, col + 1)) # the box office counts from 1
return result
if __name__ == "__main__":
hall = [
[1, 1, 0, 0, 0, 1, 0, 0],
[0, 1, 0, 1, 0, 1, 0, 1],
[0, 0, 0, 0, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 0, 0, 0],
]
print(draw_hall(hall))
print(find_seats(hall, 3))The key is to split the problem in two: first_gap walks one row counting free seats in a row (a 1 resets the count to 0) and, when it reaches n, returns where the gap started (col - n + 1). find_seats only walks the rows and turns Python indexes (from 0) into box-office numbers (from 1). Returning -1 when there is no gap avoids mixing it up with column 0, which is a valid result.
An author’s top reader
A school library keeps its data in a tuple of two dictionaries (there is a sample one in example.py):
- Books: the keys are codes (
"L-01") and the values, tuples(title, author, year, {genres}). - Members: the keys are card numbers (
"S-101") and the values, tuples(name, {codes of the books they have read}). The set can be empty.
Exercise
In main.py, write a function called top_reader that receives the data structure and an author’s name, and returns a tuple (name, count) with the member who has read the most books by that author and how many. If there is a tie, the name that comes first in alphabetical order.
- If the library has no book by that author, it returns the string
"NO AUTH". - If it has some but no member has read any, it returns
"NO READ".
Example
top_reader(example, "Carlos Ruiz Zafón") # ('Luis Martín', 3)
top_reader(example, "Gloria Fuertes") # 'NO AUTH'When you run main.py
With the solution, the if __name__ == "__main__": at the end prints:
('Luis Martín', 3)
('Ana Pérez', 1)
NO READ
NO AUTHSolution
main.py
from example import example
def top_reader(data, author):
books, members = data # unpack the tuple of two dictionaries
# 1) The codes of the author's books, in a set (so they can be crossed with &)
by_author = {code for code, (title, au, year, genres) in books.items() if au == author}
if not by_author:
return "NO AUTH"
# 2) For each member, how many of those books they have read: set intersection
best = None
for card, (name, read) in members.items():
n = len(read & by_author)
if n > 0 and (best is None or n > best[1] or (n == best[1] and name < best[0])):
best = (name, n) # tie: the name that comes first wins
if best is None:
return "NO READ"
return best
if __name__ == "__main__":
print(top_reader(example, "Carlos Ruiz Zafón"))
print(top_reader(example, "Elvira Lindo"))
print(top_reader(example, "Juan Ramón Jiménez"))
print(top_reader(example, "Gloria Fuertes"))The sets do almost all the work: first you gather the codes of the author’s books in a set (a set comprehension over books.items(), unpacking the value tuple) and then, for each member, len(read & by_author) tells you how many they have read without a second loop. The order of the checks matters: if there are no books by the author it is "NO AUTH" even if nobody has read anything. The tie is resolved in the same condition, comparing the names with <.
The times in a timetable
You have a text file with times written in several ways: H:MM or HH:MM (8:30, 09:00) or with an h instead of the colon (21h00). They always have two minute digits. A time is valid if the hours go from 0 to 23 and the minutes from 0 to 59; the ones that are not (25:10) are ignored. A number stuck to other digits (123:45) is not a time.
Exercise
Write a function called extract_times that receives two strings: the name of a text file like the one described and the name of a file that has to be created. The function finds all the valid times, normalises them to the HH:MM format and writes in the output file one line for each different time, sorted from the earliest to the latest, with the format HH:MM xN (N = times it appears).
The second-to-last line has ten hyphens (----------) and the last one, the text Total: followed by the number of valid times found (counting repeats) in a field 3 characters wide, the text , distinct: and the number of different times, also in a field of 3. If there are no times, the file has only those two lines (with 0).
Note: if instead of your own pattern you use the function re_help.find_times(), which receives a text and returns the times it contains as they appear (including the invalid ones), the maximum mark will be an 8. The file_utils.py module has read_text(name), which you can use freely.
When you run exam.py
With test_text.txt (the tab next to it), the solution creates times.txt and the if __name__ == "__main__": prints it:
08:30 x1 09:00 x1 12:15 x2 13:45 x1 14:00 x1 21:00 x1 ---------- Total: 7, distinct: 6
Solution
exam.py
import re
import re_help
from file_utils import read_text
def extract_times(source, target):
text = read_text(source)
count = {} # "HH:MM" -> times it appears
total = 0
# 1 or 2 digits, ":" or "h", 2 digits; \b avoids pieces of longer numbers (123:45)
for m in re.finditer(r"\b(\d{1,2})[:h](\d{2})\b", text):
hour, minute = int(m.group(1)), int(m.group(2))
if hour <= 23 and minute <= 59: # 25:10 and 7:75 fit the pattern, but they are not times
key = f"{hour:02d}:{minute:02d}" # normalise: 8:30 and 21h00 -> 08:30 and 21:00
count[key] = count.get(key, 0) + 1
total += 1
with open(target, "w", encoding="utf-8") as f:
for key in sorted(count): # "HH:MM" with two digits: text order is clock order
f.write(f"{key} x{count[key]}\n")
f.write("-" * 10 + "\n")
f.write(f"Total:{total:>3}, distinct:{len(count):>3}\n")
if __name__ == "__main__":
extract_times("test_text.txt", "times.txt")
print(read_text("times.txt"), end="")The pattern \b(\d{1,2})[:h](\d{2})\b finds both formats at once ([:h] is “colon or h”) and the groups separate hours and minutes, which are turned into int to check the limits. Normalising with f"{hour:02d}:{minute:02d}" makes 9:00, 09:00 and 9h00 the same key of the counter dictionary, and since all of them have two digits, sorted on the keys puts them in clock order. At the end, :>3 gives the 3-character field.
Flight codes and free seats
An airport keeps its flights in a dictionary: the keys are flight codes and the values, tuples (destination, free seats). In airport.py write these two functions (5 marks each):
1. valid_code(code) (5 marks)
Returns True if the string is a valid flight code: exactly two upper-case letters followed by 3 or 4 digits ("NT123", "IB3245"), and False in any other case ("nt123", "IB12", "IB12345", "I3B245", " IB3245"). Use a regular expression.
2. apply_bookings(flights, bookings) (5 marks)
It receives the flights dictionary and a list of tuples (code, seats) and applies the bookings in order. A booking is applied if the code is valid (use valid_code), the flight exists and it asks for between 1 and the free seats left at that moment; then those seats are subtracted in the dictionary (which ends up modified). Otherwise it is rejected. It returns a tuple (applied, rejected).
Example
flights = {"NT123": ("Tenerife Norte", 3)}
apply_bookings(flights, [("NT123", 2), ("NT123", 2)]) # (1, 1)
flights # {'NT123': ('Tenerife Norte', 1)}When you run airport.py
With the solution, the if __name__ == "__main__": at the end prints:
True False False
(3, 4)
{'NT123': ('Tenerife Norte', 0), 'IB3245': ('Madrid', 0), 'FR1234': ('London', 0)}Solution
airport.py
import re
def valid_code(code):
# 2 UPPER-CASE letters and 3 or 4 digits, and nothing else: fullmatch checks the whole string
return re.fullmatch(r"[A-Z]{2}\d{3,4}", code) is not None
def apply_bookings(flights, bookings):
applied, rejected = 0, 0
for code, seats in bookings: # in order: one booking can leave the next one without room
if valid_code(code) and code in flights and 0 < seats <= flights[code][1]:
destination, free = flights[code]
flights[code] = (destination, free - seats) # the tuple cannot be changed: it is replaced whole
applied += 1
else:
rejected += 1
return (applied, rejected)
if __name__ == "__main__":
print(valid_code("IB3245"), valid_code("IB12"), valid_code("nt123"))
flights = {"NT123": ("Tenerife Norte", 10), "IB3245": ("Madrid", 2), "FR1234": ("London", 0)}
bookings = [("NT123", 4), ("IB3245", 3), ("nt123", 1), ("FR1234", 1), ("IB3245", 2), ("UX999", 1), ("NT123", 6)]
print(apply_bookings(flights, bookings))
print(flights)re.fullmatch is the key to the first function: it forces the pattern to cover the whole string (with re.search, "XIB3245" or "IB32450" would give True). In the second, bookings are applied one by one and the dictionary is updated at each step, so the second booking sees the seats the first one left. Since the value is a tuple (immutable), it is replaced whole: flights[code] = (destination, free - seats).
Boxes inside boxes
A warehouse keeps items in boxes, and inside a box there can be other boxes. A box is represented as a list whose elements are integers (the weight in kg of an item) or other lists (inner boxes), at any depth.
Exercise
In the boxes.py module, write a recursive function called box_summary that receives a box and returns a tuple (items, weight, levels):
items: how many items there are in total, counting those in all the inner boxes.weight: the sum of their weights.levels: how many levels of boxes there are. A box with no boxes inside has 1 level (even if it is empty); if it has boxes inside, 1 more than the deepest of them.
Note: the function has to be recursive (it calls itself, or a recursive helper). If you solve it without recursion, the maximum mark will be an 8.
Example
box_summary([3, [2, 2]]) # (3, 7, 2) box_summary([]) # (0, 0, 1)
When you run boxes.py
With the solution, the if __name__ == "__main__": at the end prints:
(7, 17, 3) (0, 0, 1) (0, 0, 3)
Solution
boxes.py
def box_summary(box):
# Returns (items, total weight, levels). Each inner box is the same problem, smaller: recursion.
items, weight, deepest = 0, 0, 0 # deepest: levels of the deepest inner box
for thing in box:
if isinstance(thing, list): # another box: let the recursive call solve it
o, p, h = box_summary(thing)
items += o
weight += p
deepest = max(deepest, h)
else: # an item: add 1 and its weight
items += 1
weight += thing
return (items, weight, deepest + 1) # + 1: this box is a level too
if __name__ == "__main__":
box = [2, [1, 1, [5]], [], 3, [[4], 1]]
print(box_summary(box))
print(box_summary([]))
print(box_summary([[[]]]))Each inner box is the same problem, smaller: the recursive call returns its tuple and you only need to add it. The base case does not need to be written separately: a box with no boxes inside makes no calls and the loop simply ends. Levels are the trickiest part: you keep the maximum of the inner levels (not the sum) and add 1 for the current box; that is why [] gives 1 and [[[]]], 3.
Buses between two stops
A bus company keeps its data in a tuple of two dictionaries (there is a sample one in example.py):
- Routes: the keys are route numbers (strings:
"12") and the values, tuples(name, [codes of the stops in order], {days it runs}). The days are"Mo","Tu","We","Th","Fr","Sa"and"Su". Each route goes one way only: from the first code in the list to the last. - Stops: the keys are codes (
"P03") and the values, tuples(name, {numbers of the routes that stop there}).
Exercise
In main.py, write a function called routes_between that receives the data structure, an origin stop code, a destination stop code and a day, and returns a list of tuples (route, stops) with the routes that on that day take you from the origin to the destination in that direction and how many stops you move forward. Sort it from fewest to most stops and, on a tie, by route number (as a number: "3" comes before "12").
- If the origin is not a stop, it returns the string
"NO ORIG"; if the destination is not,"NO DEST"(the origin is checked first). - If no route works, it returns
"NO TRIP".
Example
routes_between(example, "P01", "P03", "Su") # [('1', 2)] (route 17 does not run on Sunday)When you run main.py
With the solution, the if __name__ == "__main__": at the end prints:
[('1', 2), ('17', 2)]
[('1', 2)]
[('12', 1)]
NO TRIP
NO ORIGSolution
main.py
from example import example
def routes_between(data, origin, destination, day):
routes, stops = data
if origin not in stops:
return "NO ORIG"
if destination not in stops:
return "NO DEST"
# Only the routes that stop at both can work: set intersection
shared = stops[origin][1] & stops[destination][1]
trips = []
for route in shared:
name, path, days = routes[route]
if day in days:
i = path.index(origin)
j = path.index(destination)
if i < j: # the bus goes in that direction
trips.append((route, j - i))
if not trips:
return "NO TRIP"
# Fewest stops first; on a tie, by route number (int: "3" comes before "12")
return sorted(trips, key=lambda v: (v[1], int(v[0])))
if __name__ == "__main__":
print(routes_between(example, "P01", "P03", "Sa"))
print(routes_between(example, "P01", "P03", "Su"))
print(routes_between(example, "P05", "P03", "Mo"))
print(routes_between(example, "P07", "P05", "Mo"))
print(routes_between(example, "P99", "P01", "Mo"))The stops dictionary already says which routes go through each one, so the intersection of both sets gives the candidates without walking all the routes. For each candidate you check the day (in on the set) and the direction: index gives the position of each stop on the path and it only counts if the origin comes first (i < j); the difference is the number of stops. The order needs a double key and int(...): sorting the routes as text, "12" would come before "3".
Email addresses by domain
You have a text file with email addresses mixed in with the text. An address is: one or more characters that can be letters, digits, _, ., + or -; an @; and a domain made of letters, digits or - with at least one dot (gmail.com, ulpgc.es). The full stop that ends a sentence is not part of the address. Two addresses that only differ in upper and lower case are the same.
Exercise
Write a function called count_domains that receives two strings: the name of a text file like the one described and the name of a file that has to be created. The function finds the addresses, turns them into lower case (without repeats) and writes in the output file one line per domain (what comes after the @) with the domain left-aligned in a field of 15 characters and the number of different addresses of that domain in a field of 3. The lines go from most to fewest addresses and, on a tie, by the domain in alphabetical order.
The second-to-last line has ten = signs and the last one, Emails: followed by the number of different addresses (field of 3), , domains: and the number of domains (field of 3).
Note: if instead of your own pattern you use re_help.find_emails(), which receives a text and returns the list of addresses as they appear, the maximum mark will be an 8. In file_utils.py you have read_text(name).
When you run exam.py
With test_text.txt, the solution creates domains.txt and the if __name__ == "__main__": prints it:
gmail.com 2 guaguas.es 2 hotmail.com 1 ulpgc.es 1 ========== Emails: 6, domains: 4
Solution
exam.py
import re
import re_help
from file_utils import read_text
def count_domains(source, target):
text = read_text(source)
# user (letters, digits, _ . + -) @ domain with at least one dot; a sentence's final full stop is not included
emails = {c.lower() for c in re.findall(r"[\w.+-]+@[\w-]+(?:\.[\w-]+)+", text)} # set: no repeats
per_domain = {}
for c in emails:
domain = c.split("@")[1]
per_domain[domain] = per_domain.get(domain, 0) + 1
# most addresses first; on a tie, the domain in alphabetical order
order = sorted(per_domain.items(), key=lambda par: (-par[1], par[0]))
with open(target, "w", encoding="utf-8") as f:
for domain, n in order:
f.write(f"{domain:<15}{n:>3}\n")
f.write("=" * 10 + "\n")
f.write(f"Emails:{len(emails):>3}, domains:{len(per_domain):>3}\n")
if __name__ == "__main__":
count_domains("test_text.txt", "domains.txt")
print(read_text("domains.txt"), end="")The pattern has three parts: [\w.+-]+ (the user), @ and [\w-]+(?:\.[\w-]+)+ (the domain: a piece and, at least once, dot + piece). Since a piece has to follow each dot, the full stop that ends the sentence is left out. Turning the addresses into lower case inside a set comprehension removes repeats in one go; then you count per domain with the counter pattern and sort with the key (-n, domain).
Rotate a matrix and save it
A matrix is a list of rows, all of the same length, with whole numbers. In matrices.py write these two functions (5 marks each):
1. rotate(matrix) (5 marks)
Returns a new matrix with the matrix rotated 90° to the right (clockwise): a matrix with r rows and c columns gives another one with c rows and r columns. The original matrix is not changed. An empty matrix ([]) gives [].
2. save(matrix, name) (5 marks)
It creates a text file with that name and writes each row of the matrix on a line, with each number right-aligned in a field of 4 characters (no separators). The last line is Rows: r, columns: c. With the empty matrix, only that line (Rows: 0, columns: 0).
Example
rotate([[1, 2], [3, 4]]) # [[3, 1], [4, 2]]
When you run matrices.py
With the solution, the if __name__ == "__main__": at the end prints:
[[4, 1], [5, 2], [6, 3]] [[1, 2, 3], [4, 5, 6]] 4 1 5 2 6 3 Rows: 3, columns: 2
Solution
matrices.py
def rotate(matrix):
# Rotates 90° clockwise: column c (read bottom to top) becomes row c. It does not touch the original.
if not matrix:
return []
rows, cols = len(matrix), len(matrix[0])
new = []
for c in range(cols):
new.append([matrix[f][c] for f in range(rows - 1, -1, -1)]) # f goes from the last row to the first
return new
def save(matrix, name):
with open(name, "w", encoding="utf-8") as out:
for row in matrix:
out.write("".join(f"{x:>4}" for x in row) + "\n") # each number in a field of 4
cols = len(matrix[0]) if matrix else 0
out.write(f"Rows: {len(matrix)}, columns: {cols}\n")
if __name__ == "__main__":
m = [[1, 2, 3], [4, 5, 6]]
g = rotate(m)
print(g)
print(m)
save(g, "rotated.txt")
print(open("rotated.txt", encoding="utf-8").read(), end="")When rotating to the right, column c of the original, read from bottom to top, is row c of the new one; that is why the outer loop walks the columns and the inner comprehension goes from the last row to the first (range(rows - 1, -1, -1)). Building new lists with append and comprehensions guarantees that the original does not change. In save, f"{x:>4}" right-aligns each number in 4 characters, and the empty matrix needs its own case (it has no matrix[0]).
Temperatures of the week
A weather station in Gran Canaria stores each day’s readings in a matrix: row i has the temperatures (integers or float) measured on day i, and it can have any length, including no readings if the sensor failed. The names of the days come separately, in a tuple with as many elements as the matrix has rows.
Exercise
In the temperatures.py module, write a function called week_summary that receives the tuple of days and the matrix, and returns a list of tuples (day, low, high, mean), one per day and in the same order. The mean is rounded to 1 decimal with round. If a day has no readings, its tuple is (day, None, None, None).
Note: you are advised to write a helper function that summarises one day; if you do not write it (and use it from week_summary), the maximum mark will be an 8.
Example
week_summary(("Monday", "Tuesday"), [[20, 23], []])
# [('Monday', 20, 23, 21.5), ('Tuesday', None, None, None)]When you run temperatures.py
The table.py module (already written) prints the summary as a table. With the solution, the if __name__ == "__main__": at the end prints:
[('Monday', 18, 24, 21.4), ('Tuesday', None, None, None), ('Wednesday', 17, 25, 20.9)]
Day Min Max Mean
Monday 18 24 21.4
Tuesday no data
Wednesday 17 25 20.9Solution
temperatures.py
from table import print_summary
def day_summary(readings):
# (low, high, mean with 1 decimal) of one day, or (None, None, None) if there are no readings.
if not readings: # without this, sum([]) / len([]) would divide by zero
return (None, None, None)
return (min(readings), max(readings), round(sum(readings) / len(readings), 1))
def week_summary(days, temperatures):
summary = []
for i in range(len(days)): # row i of the matrix is day i of the tuple
low, high, mean = day_summary(temperatures[i])
summary.append((days[i], low, high, mean))
return summary
if __name__ == "__main__":
days = ("Monday", "Tuesday", "Wednesday")
temperatures = [[18, 21.5, 24, 22], [], [17, 19, 23.5, 25, 20]]
summary = week_summary(days, temperatures)
print(summary)
print_summary(summary)Row i of the matrix goes with element i of the tuple, so you walk them by index (or with zip). The helper day_summary solves one day and has a special case: with an empty list, min raises ValueError and sum / len divides by zero, so you check it first. round(x, 1) rounds the mean without changing the float type.
The short film festival winner
A short film festival keeps the audience’s votes in a tuple of two dictionaries (there is a sample one in example.py):
- Shorts: the keys are codes (
"C3") and the values, tuples(title, director, category). - Voters: the keys are ID numbers and the values, tuples
(name, {short code: points}), with whole points from 1 to 5. Each voter scores the shorts they want.
Exercise
In main.py, write a function called category_winner that receives the data structure and a category, and returns a tuple (title, mean, votes) of the short in that category with the highest mean score (rounded to 2 decimals with round) and how many votes it has. Only shorts with at least one vote count. If the mean ties, the one with more votes wins and, if it still ties, the title that comes first in alphabetical order.
- If there is no short in that category, it returns the string
"NO CAT". - If there are some but none has votes, it returns
"NO VOTE".
Example
category_winner(example, "documentary") # ('Alisios', 5.0, 1)When you run main.py
With the solution, the if __name__ == "__main__": at the end prints:
('Bajamar', 4.67, 3)
('Alisios', 5.0, 1)
NO VOTE
NO CATSolution
main.py
from example import example
def category_winner(data, category):
shorts, voters = data
in_cat = {code for code, (title, director, cat) in shorts.items() if cat == category}
if not in_cat:
return "NO CAT"
# Gather the votes of each short in the category: code -> [points, points…]
votes = {}
for vid, (name, points) in voters.items():
for code, p in points.items():
if code in in_cat:
votes.setdefault(code, []).append(p)
if not votes:
return "NO VOTE"
best = None
for code, plist in votes.items():
mean = sum(plist) / len(plist) # the exact mean is compared, not rounded
key = (-mean, -len(plist), shorts[code][0]) # higher mean, more votes, earlier title
if best is None or key < best[0]:
best = (key, code, mean, len(plist))
key, code, mean, n = best
return (shorts[code][0], round(mean, 2), n)
if __name__ == "__main__":
print(category_winner(example, "fiction"))
print(category_winner(example, "documentary"))
print(category_winner(example, "horror"))
print(category_winner(example, "musical"))It is done in three steps: the set of shorts in the category, a dictionary code → list of points walking the voters (setdefault creates the list the first time) and the search for the best one. The three criteria fit in a single key tuple (-mean, -votes, title): comparing tuples compares element by element, so the smallest one is the winner. The exact mean is compared and it is only rounded when returned; rounding earlier, 4.666… and another short’s 4.67 would look the same.
The shopping receipt
You have the text of a supermarket receipt. A line is a product line if it ends in a price: euros (one or more digits), a comma or a dot, two cent digits and € or EUR (with or without a space before it and maybe spaces at the end). Between the name and the price there may be filler dots or spaces (Whole milk .......... 1,15 €). The other lines (header, goodbye…) are ignored.
Exercise
Write a function called summarise_receipt that receives two strings: the name of a file like the one described and the name of a file that has to be created. For each product, in the order of the receipt, it writes a line with the name (without the filler or the spaces at both ends) left-aligned in a field of 16 characters and the price with a dot and two decimals right-aligned in a field of 7.
Then, a line of 23 = signs, another with TOTAL in the field of 16 and the sum of the prices in the field of 7, and the last one with Items: and the number of products in a field of 3. Watch out for float numbers: work in cents.
Note: if instead of your own pattern you use re_help.find_price(), which receives a line and returns (name, price) or None, the maximum mark will be an 8. In file_utils.py you have read_text(name).
When you run exam.py
With test_text.txt, the solution creates summary.txt and the if __name__ == "__main__": prints it:
Whole milk 1.15 Corn bread 0.80 Eggs (12) 2.35 Local potatoes 3.40 ======================= TOTAL 7.70 Items: 4
Solution
exam.py
import re
import re_help
from file_utils import read_text
def summarise_receipt(source, target):
lines = []
total = 0 # in cents: with integers there are no rounding errors
for line in read_text(source).split("\n"):
# name (as short as possible), filler dots or spaces, euros, comma or dot, 2 cents, € or EUR at the end
m = re.match(r"^(.*?)[\s.]*(\d+)[,.](\d{2})\s*(?:€|EUR)\s*$", line)
if m:
cents = int(m.group(2)) * 100 + int(m.group(3))
total += cents
lines.append((m.group(1).strip(), cents))
with open(target, "w", encoding="utf-8") as f:
for name, c in lines:
f.write(f"{name:<16}{c // 100:>4}.{c % 100:02d}\n") # 4 euro digits + . + 2 cent digits = 7
f.write("=" * 23 + "\n")
f.write(f"{'TOTAL':<16}{total // 100:>4}.{total % 100:02d}\n")
f.write(f"Items:{len(lines):>3}\n")
if __name__ == "__main__":
summarise_receipt("test_text.txt", "summary.txt")
print(read_text("summary.txt"), end="")Everything is in the line pattern: ^(.*?) takes the shortest possible name (lazy), [\s.]* eats the filler, (\d+)[,.](\d{2}) separates euros and cents and \s*(?:€|EUR)\s*$ forces the line to end in the currency; that way the numbers in the name (2x1, (12)) are not mistaken for the price. Adding in whole cents avoids 1.15 + 0.80 + 2.35 + 3.40 giving 7.699999999999999; to write it, c // 100 and c % 100:02d.
Digit sums and groups
In digits.py write these two functions (5 marks each):
1. digit_sum(n) (5 marks)
It receives an integer n ≥ 0 and returns the sum of its digits (digit_sum(4721) = 4 + 7 + 2 + 1 = 14). It has to be recursive and work with numbers (% and //), without turning n into a string. If it is not recursive, this function is worth at most 3.5 of its 5 marks.
2. group_by_sum(numbers) (5 marks)
It receives a list of integers ≥ 0 and returns a dictionary whose keys are the digit sums and whose values are sorted lists from smallest to largest with the numbers in the list that have that sum, without repeats. Use digit_sum. With the empty list, {}.
Example
group_by_sum([11, 2, 20, 11]) # {2: [2, 11, 20]}When you run digits.py
With the solution, the if __name__ == "__main__": at the end prints:
14 0 9
{10: [19, 28], 5: [5, 14, 23], 1: [100]}Solution
digits.py
def digit_sum(n):
# Base case: a one-digit number is its own sum. Otherwise, the last digit + the sum of the rest.
if n < 10:
return n
return n % 10 + digit_sum(n // 10) # 4721 -> 1 + sum(472) -> 1 + 2 + sum(47)…
def group_by_sum(numbers):
groups = {}
for n in numbers:
s = digit_sum(n)
if s not in groups:
groups[s] = []
if n not in groups[s]: # no repeats
groups[s].append(n)
for s in groups:
groups[s].sort() # each list, from smallest to largest
return groups
if __name__ == "__main__":
print(digit_sum(4721), digit_sum(0), digit_sum(9))
print(group_by_sum([19, 28, 5, 14, 23, 28, 100]))digit_sum shrinks the problem by removing the last digit: n % 10 is that digit and n // 10 the number without it, which is the same problem, smaller; the base case is a one-digit number (including 0). In group_by_sum, each number goes to the list for its sum (created the first time), not in avoids repeats and, at the end, each list is sorted. Sorting the input list first would also work, but you must not change the caller’s list.
The first time you press Run or Evaluate, the browser downloads Python (about 12 MB). It takes a few seconds; after that it is fast and 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). When you hand in, the draft is deleted.
What the FP1 practical exam is like
The FP1 practical exams were done in VPL, the programming activity of aep26 (the exams Moodle). Each one is one exercise: a statement with the context (which data structure you are given), the function you have to write, an example and some automatic tests that give the mark. There were two sittings with different statements; here you have three versions of each exam.
| Exam | What they ask for | Files | Time | Marks |
|---|---|---|---|---|
| Exam 1 | One function on lists, matrices and tuples (with a helper or recursive) | cinema.py + a drawing module | 35 min | 10 |
| Exam 2 | One function on nested dictionaries, tuples and sets, with error answers ("NO AUTH"…) | main.py + example.py with the data | 40 min | 10 |
| Exam 3 | One function with regular expressions that reads a file and writes another with formatting | exam.py + test_text.txt + help modules | 40 min | 10 |
| Resit | One file with two functions from the whole syllabus | One .py | 40 min | 5 + 5 |
What surprises you most the first time is the time: 35 or 40 minutes for one function sounds like a lot, but between reading the statement, understanding the data structure and fighting the odd cases, it flies. This drawing is exactly what you will see in the environment:
Notice one difference with FP2: here there is no separate tryout file. The .py you complete comes with an if __name__ == "__main__": at the end with the example from the statement; Run launches that file and shows you what it prints. You can change that block to try your own cases: it is not marked. The Evaluate tests import your function and call it with their own data.
Before writing a single line, press Run with the file as it is. You will see the NameError of the missing function, but you will also check that Python is loaded and that the given files work.
What each exam covers
The continuous-assessment exams followed the pace of the course: the first one, around week 8 (after Recursion); the second one, at the end of Associative containers; and the third one, with Strings, Regular expressions and Text files. The resit can touch anything. This is what comes up and where to revise it:
| Exam | Topics | Mock exam versions | Revise with |
|---|---|---|---|
| Exam 1 | T02-T10: functions, lists and tuples, matrices, recursion | A Free seats at the cinema · B Boxes inside boxes (recursive) · C Temperatures of the week | Lists and tuples, Matrices, Recursion |
| Exam 2 | T11: associative containers | A An author’s top reader · B Buses between two stops · C The short film festival winner | Associative containers |
| Exam 3 | T12-T14: strings, regex and files | A The times in a timetable · B Email addresses by domain · C The shopping receipt | Strings, Regular expressions, Text files |
| Resit | The whole syllabus | A Flight codes and free seats · B Rotate a matrix and save it · C Digit sums and groups | The three above and Functions |
The statements are original: the real ones only told me which data structure they gave, what was asked and how much time there was. If you want to revise the test part, there is the FP1 theory mock exam.
How it is marked
Each exercise has 5 or 6 weighted tests that add up to 10. A test calls your function with some data and compares what it returns (or what it writes to the file) with what is expected; if it matches, you add its weight; if not, you get nothing from that test and a comment tells you what failed. The mark is the sum of the weights of the tests you pass.
A real example: if in Temperatures of the week you forget that a day may have no readings, min([]) raises an error and the two tests with an empty day fail. The environment tells you like this:
1: Your code raises ValueError: min() iterable argument is empty (temperatures.py, line 7). 3: Your code raises ValueError: min() iterable argument is empty (temperatures.py, line 7).
Those two tests are worth 2.5 and 1.5, so the mark is 10 − 2.5 − 1.5 = 6. A single forgotten case, four marks gone.
The rule of 8
In almost every real exam there was a note like «you are advised to write a helper function; if you do not, the maximum mark will be an 8», or «if you use the help function instead of your own pattern, the maximum mark will be an 8». In the mock exam, that rule is one more test worth 2 marks:
- Exam 1 (A and C): the requested function has to call a helper function of yours.
- Exam 1 (B): the function has to be recursive (it calls itself or a recursive helper).
- Exam 3: you cannot use the help module (
re_help), which gives you the pattern ready-made. - Resit C:
digit_sumhas to be recursive (1.5 of its 5 marks).
That test only counts if the result is also right, so an empty helper gains you nothing. If in Free seats you do everything inside find_seats, you pass every test except that one and get an 8:
Evaluations count
As in the VPL, you can evaluate as often as you like, but the first 10 of each exercise are free and, from the 11th on, each one subtracts 0.1 from that exercise’s mark. The final marking when you hand in does not count. Some numbers so you can see it:
| Evaluations | Penalty | If the tests give 10 |
|---|---|---|
| 1-10 | 0 | 10 |
| 12 | 2 × 0.1 = 0.2 | 9.8 |
| 15 | 5 × 0.1 = 0.5 | 9.5 |
| 20 | 10 × 0.1 = 1 | 9 |
Evaluating after every line you change. Use Run (which does not count) to try the example and your own cases, and save the evaluations for when you think it is ready.
How to use the environment
- Run launches your
.py(its__main__) and shows the output in the console. If there is an error, you get the traceback and a «Go to <file>, line N» button. - Evaluate runs the tests and shows each one with a pass or fail mark, the mark and the evaluation counter.
- Helpers: in the mock exam they start switched off (no autocomplete or bracket closing), as in the VPL. You can switch them on, but get used to programming without them.
- Cheat sheet: opens the Python cheat sheet and, in exam 3 and the resit, the regex, files and formatting one too.
- Full window: the exam takes up the whole screen; drag the dividers to give more room to the statement or the console, use Full screen (the four-corners button) to fill the whole screen and Article to read this text again without losing the clock.
- Hand in marks the last version of each exercise and gives you the mark, with the solution and its explanation.
On a phone, the exam is split into three tabs: Statement, Code and Result. It can be done, but the real exam is with a keyboard: practice on a computer. And if you want to program without a clock, the same environment is free in Python playground.
How to split your time
With 35 or 40 minutes there is no room to start from scratch twice. A split that works:
- Read (4-6 min): understand the data structure. Write in a comment what each thing is (
books: code -> (title, author, year, {genres})) and what the function returns in each case, including the error ones. - Program (14-18 min): first the normal case, which is the one in the example; press Run and compare with the output in the statement.
- Evaluate and fix (10-12 min): evaluate and read the comments of the failing tests. Each comment tells you which case you are missing.
- Review (5-6 min): edge cases (empty, tie, a single element), the rule of 8 and that no test
printis left inside the function.
In the resit there are two 5-mark functions in the same time: do the one you see more clearly first, evaluate it and move on to the other. One whole function is worth more than two halves.
The cases that fail most
The tests of each version are designed for the usual mistakes. These are the ones that cost the most marks:
| Exam | Case | What happens if you forget it |
|---|---|---|
| 1 | Empty list or matrix, row without a gap, day without readings | IndexError, ValueError from min/max or division by zero |
| 1 | Numbering from 1 (rows, seats) | Everything is shifted by one position |
| 2 | The order of the error answers ("NO ORIG" before "NO DEST") | You return the wrong error |
| 2 | Ties and numeric order of text ("3" before "12") | sorted puts "12" before "3" |
| 2 | Changing the data you are given | The tests that check it does not change fail |
| 3 | \b and the limits of the pattern | You take pieces of longer numbers (123:45) |
| 3 | Upper case, repeats and a sentence’s final full stop | You count the same address twice or put the full stop in the domain |
| 3 | Amounts with float | 1.15 + 0.80 + 2.35 + 3.40 gives 7.699999999999999: work in cents |
| 3 | The newline of write | All the lines stuck together: write does not add it |
| Resit | search instead of fullmatch | "XIB3245" looks like a valid code |
Common mistakes
- Returning a list when a tuple is asked for (or the other way round).
[('Monday', 18, 24, 21.4)]is not equal to[['Monday', 18, 24, 21.4]]: the tests compare types. - Printing instead of returning. If your function does
print(result)and notreturn result, the test getsNone. - Opening the file without
encoding="utf-8". In the exam the text has accents and «€»: always give it the encoding. - Rounding before comparing. In The short film festival winner, comparing means that are already rounded can pick the wrong short: round only when you return.
- A helper that is not used. The rule of 8 checks that the requested function calls it: writing it and not using it does not count.
- Leaving the
if __name__ == "__main__":broken. It is not marked, but if it has a syntax error, the whole file fails.
Writing the function inside the if __name__ == "__main__":. The tests import your module and that block does not run on import: the function would not exist. Write it above, outside it.
Watch it step by step in Python Tutor
Python Tutor runs the code line by line and draws the variables, the lists and the call stack. Choose Python 3. This is the solution to Boxes inside boxes with a small box, perfect to see recursion in action:
def box_summary(box):
items, weight, deepest = 0, 0, 0
for thing in box:
if isinstance(thing, list):
o, p, h = box_summary(thing)
items += o
weight += p
deepest = max(deepest, h)
else:
items += 1
weight += thing
return (items, weight, deepest + 1)
box = [2, [1, [5]]]
print(box_summary(box))
(3, 8, 3)
What to watch step by step:
- In the first call,
thingis2: it is an item, soitemsbecomes 1 andweight2. - With
[1, [5]]a second frame ofbox_summaryappears on top of the first one: the outer call waits on theo, p, h = …line. - Inside,
[5]opens a third frame. It is the deepest box: it returns(1, 5, 1)because it has no boxes inside (deepestis still 0). - On the way back, the second frame adds
(1, 5, 1)to its own and returns(2, 6, 2); the first one adds it and returns(3, 8, 3). Notice thatdeepestkeeps the maximum, not the sum.
Cheat sheet: what you could check
In the exam you could check a Python 3 cheat sheet and, in the third one, a regular expressions, files and formatting one. These are ours, covering the same things in our own words. In the mock exam you have them on the Cheat sheet button of the environment.
Python cheat sheet FP1
What you could check in the exam, in our own words: syntax, strings, lists, matrices, dictionaries, sets and functions.
The basics
x = 7; y = 2.5; s = "hello"; ok = Trueint, float, str and bool7 // 2 → 3 7 % 2 → 1 2 ** 3 → 8 7 / 2 → 3.5floor division, remainder, power and divisionint("42") float("3.5") str(7) round(2.675, 2)convert and roundif x > 0 and not done: … elif …: … else: …and, or, not; elif chainsfor i in range(1, 10, 2): … while n > 0: …range(start, end not included, step)break continue passleave the loop, skip to the next turn, do nothingStrings
s.upper() s.lower() s.strip() s.title()return another string (they are immutable)s.split(",") "-".join(parts)split into a list / join a list of stringss.find("ab") → -1 si no está s.count("a") s.replace("a", "b")find does not raise; index doess[1:4] s[-1] s[::-1] len(s)slice, last character, reversed, lengthc.isdigit() c.isalpha() c.isupper() "ab" in scheck characters and containmentLists and tuples
l.append(x) l.insert(0, x) l.pop() l.remove(x)append, insert, pop the last, remove a valuesorted(l, reverse=True) l.sort() sorted(l, key=lambda t: t[1])sorted returns another; sort changes the same onet = (3, "a") a, b = t (5,)tuple: immutable; it unpacks; a one-item tuple needs a comma[x * 2 for x in l if x > 0]comprehension with a filterb = l[:] b = list(l) import copy; copy.deepcopy(m)shallow copy and deep copy (nested lists)sum(l) max(l) min(l) len(l) enumerate(l, 1) zip(a, b)handy built-in functionsMatrices (lists of lists)
m = [[0] * 3 for _ in range(2)]create 2 × 3 (never [[0] * 3] * 2: shared rows)len(m) len(m[0]) m[f][c]rows, columns and one elementfor f in range(len(m)):
for c in range(len(m[f])): …walk by indexes[[m[f][c] for f in range(len(m))] for c in range(len(m[0]))]transposeDictionaries and sets
d = {"a": 1} d["b"] = 2 d.get(k, 0) k in dget with a default; in looks at the keysfor k, v in d.items(): … d.keys() d.values() d.pop(k)walk and deleted[k] = d.get(k, 0) + 1 d.setdefault(k, []).append(x)count and groups = set() s.add(x) a | b a & b a - bset: no repeats; union, intersection, difference{k: v for k, v in d.items() if v > 0} {x % 3 for x in l}dictionary and set comprehensionFunctions and recursion
def f(a, b=1): return a + bdefault parameter; without return it returns Nonereturn x, y → a, b = f()return several values (it is a tuple)def fact(n):
if n <= 1: return 1
return n * fact(n - 1)base case first; the call gets closer to the base caseisinstance(x, list)know whether an element is another list (nested structures)if __name__ == "__main__": …what only runs when that file is launchedRegex, files and formatting cheat sheet FP1
The cheat sheet of the third exam and the resit, in our own words: patterns, re functions, files and formatting with width.
Patterns
\d \w \s \D \W \Sdigit, letter/digit/_, space; in upper case, the opposite. [aeiou] [A-Z0-9] [^,]any character, one from the list, range, any except+ * ? {3} {2,4}one or more, zero or more, optional, exactly 3, from 2 to 4+? *?lazy version: as short as possible^ $ \bstart, end and word boundary(\d+) (?:ab)+ a|b \.group, non-capturing group, alternative, a real dotr"\d{8}[A-Z]"write patterns as r"…" stringsre functions
re.search(p, s) re.match(p, s) re.fullmatch(p, s)anywhere, at the start, the whole string (None if not)re.findall(p, s)list of matches (with groups: tuples of groups)for m in re.finditer(p, s): m.group(0), m.group(1), m.start()walk the matches with their groupsre.sub(p, r"\1-\2", s) re.split(r"[,;]\s*", s)replace (with groups) and splitre.findall(p, s, re.IGNORECASE)case-insensitiveText files
with open("data.txt", encoding="utf-8") as f:
texto = f.read()read everything (it closes by itself)for line in f: line.rstrip("\n")line by line (each with its newline)f.readlines() texto.split("\n")list of lineswith open("out.txt", "w", encoding="utf-8") as f:
f.write(f"{x}\n")"w" creates or empties; "a" appends; write adds no newlineFileNotFoundErrorthe file does not exist (are you in the right folder?)Formatting
f"{n:>3}" f"{s:<16}" f"{s:^10}"right in 3, left in 16, centred in 10f"{x:.2f}" f"{x:8.2f}" f"{n:02d}"2 decimals, in 8 with 2 decimals, 2 digits with zeros"=" * 10 "{:>5}".format(n)repeat a character; format as an alternativec // 100, c % 100 → f"{c // 100}.{c % 100:02d}"amounts in cents, without float errorsSummary
| Exam | Time | What cannot be missing |
|---|---|---|
| Exam 1 | 35 min | The helper function (or the recursion) and the empty cases |
| Exam 2 | 40 min | Unpacking the tuples properly, the error answers in their order and not changing the data |
| Exam 3 | 40 min | Your own pattern, the formatting with width and the newline of each write |
| Resit | 40 min | Two 5-mark functions: finish one before starting the other |
Three ideas to keep:
- The mark is the sum of the tests you pass: one forgotten case (empty, tie) can bring down several at once.
- The rule of 8 is a 2-mark test: the helper that gets called, the recursion or your own pattern.
- Run a lot and evaluate little: from the 11th evaluation, each one costs 0.1.
Once you have it, try the test part in the FP1 theory mock exam, or see all the mock exams in Exams.
Keep goingAll Python articlesDid this article help you? Here is how you can support SergioLearns →



