Work it out
After this: Write the average, the top student and the class average as three functions and run them.
On this page · 6 sections · 3 checks
The book holds three names and their marks. The teacher wants three numbers from it: each student's average, the top student, and the class average. Three jobs, so stage 2 writes three functions, each small enough to check on its own.
The average of one list
The average of a list of marks is their total divided by how many there are. "Lists" worked this out for one list; here it becomes a function, average, that takes any list of marks and gives the number back. For Ana, 72 + 85 is 157, and 157 / 2 is 78.5. For Ben, 150 / 2 is 75.0.
def average(marks): return sum(marks) / len(marks)
print(average([72, 85]))print(average([90, 60]))run the program to see its boxes
nothing printed yetPress Run it, then step through the program one line at a time.
- lines
- 0
- prints
- 0
- calls
- 0
The top student
To find the best, keep the best seen so far and replace it whenever a bigger one comes along, the pattern "Lists" used to find the biggest mark. Two boxes do it: best holds a name and best_averagebestAverage holds that student's average. They start at an empty name and -1, a value every real average beats, so that the first student always takes the lead.
- Ana's average, 78.5, beats -1.
bestbecomes Ana, and the best average becomes 78.5. - Ben's 75.0 does not beat 78.5. Nothing changes.
- Cy's 90.0 beats 78.5.
bestbecomes Cy, and the best average becomes 90.0.
The loop goes through the book's keys, one name at a time: for name in book gives each key in turn.for (String name : book.keySet()) gives each key in turn. To keep the trace short, the piece below starts from the three averages already worked out; in the program the loop calls average on each student's marks in their place.
averages = {"Ana": 78.5, "Ben": 75.0, "Cy": 90.0}best = ""best_average = -1for name in averages: if averages[name] > best_average: best = name best_average = averages[name]print(best)run the program to see its boxes
nothing printed yetPress Run it, then step through the program one line at a time.
- lines
- 0
- prints
- 0
- calls
- 0
The class average
The class average is the total of the three averages divided by three: (78.5 + 75.0 + 90.0) / 3, which is 81.1666…. Every student here has two marks, so adding all six marks and dividing by six would give the same number. The function goes through the book's keys, adds up each student's average, and divides by how many students there are.
Stage 2
def load(filename): book = {} with open(filename) as f: lines = f.readlines() for line in lines: try: parts = line.strip().split(",") book[parts[0]] = [int(parts[1]), int(parts[2])] except ValueError: print("Skipping bad line: " + line.strip()) return book
def average(marks): return sum(marks) / len(marks)
def top_student(book): best = "" best_average = -1 for name in book: if average(book[name]) > best_average: best = name best_average = average(book[name]) return best
def class_average(book): total = 0 for name in book: total = total + average(book[name]) return total / len(book)
book = load("marks.txt")print(average(book["Ana"]))print(average(book["Ben"]))print(average(book["Cy"]))print("Top student: " + top_student(book))print(class_average(book))78.5 75.0 90.0 Top student: Cy 81.16666666666667
import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;import java.util.HashMap;import java.util.List;
public class Main { static HashMap<String, List<Integer>> load(String filename) throws IOException { HashMap<String, List<Integer>> book = new HashMap<>(); List<String> lines = Files.readAllLines(Path.of(filename)); for (String line : lines) { try { String[] parts = line.split(","); book.put(parts[0], List.of(Integer.parseInt(parts[1]), Integer.parseInt(parts[2]))); } catch (NumberFormatException e) { System.out.println("Skipping bad line: " + line); } } return book; }
static double average(List<Integer> marks) { int total = 0; for (int m : marks) { total = total + m; } return (double) total / marks.size(); }
static String topStudent(HashMap<String, List<Integer>> book) { String best = ""; double bestAverage = -1; for (String name : book.keySet()) { if (average(book.get(name)) > bestAverage) { best = name; bestAverage = average(book.get(name)); } } return best; }
static double classAverage(HashMap<String, List<Integer>> book) { double total = 0; for (String name : book.keySet()) { total = total + average(book.get(name)); } return total / book.size(); }
public static void main(String[] args) throws IOException { HashMap<String, List<Integer>> book = load("marks.txt"); System.out.println(average(book.get("Ana"))); System.out.println(average(book.get("Ben"))); System.out.println(average(book.get("Cy"))); System.out.println("Top student: " + topStudent(book)); System.out.println(classAverage(book)); }}78.5 75.0 90.0 Top student: Cy 81.16666666666667
The load function is the one from stage 1, unchanged. The three new functions sit under it, and the last lines call them and print what comes back. The class average prints as 81.16666666666667: a long number, but the right one. Making it readable is stage 4's job.
Change the -1 in the top-student function to 100 and run it again: no average beats 100, so best stays empty.
Check yourself
What does this program print?
def average(marks): return sum(marks) / len(marks)
print(average([80, 90]))import java.util.List;
public class Main { static double average(List<Integer> marks) { int total = 0; for (int m : marks) { total = total + m; } return (double) total / marks.size(); }
public static void main(String[] args) { System.out.println(average(List.of(80, 90))); }}Ben's line in the file changes to Ben,95,95; Ana and Cy stay as they were. What does stage 2 print after Top student:?
The school decides that the top student should be the one with the highest single mark, not the highest average. Which function changes?
Honesty notes
- Write each job as a small function: average of a list, the top student, the class average.
- Find the best with the best-so-far pattern: start below every possible average, and replace the best whenever a bigger one comes along.
- Go through a dictionary with a loop over its keys (for name in book in Python, book.keySet() in Java).
- Say that the class average of 81.16666666666667 is right, and that making it readable is a later stage's job.