Make it a class
After this: Replace each dictionary entry with a Student object that knows its own average.
On this page · 6 sections · 3 checks
In stage 2, a student is a key and a value that live apart: every function has to write book[name]book.get(name) to get from the name to the marks, and the average belongs to nobody in particular. "Classes and objects" gave a better shape for a thing with several pieces of data and something it can do. A student has a name and marks, and can tell you its average.
The Student class
The class has a constructor that stores the name and the marks, and an average method. The method is the stage 2 function with one change: it takes no list, because the student's own marks are self.marksmarks, reached through this.
Student("Ana", [72, 85])makes a new object. The constructor runs with it as selfthis, and stores the name and the marks inside it.ana.namereads the name back:Ana.ana.average()runs the method withanaas selfthis. It adds up that object's marks and divides: 78.5.
- Run the programRun the program and step through it. Watch the constructor fill the new object's name and marks, then watch the average method run with that object as self (this in Java).
class Student: def __init__(self, name, marks): self.name = name self.marks = marks
def average(self): return sum(self.marks) / len(self.marks)
ana = Student("Ana", [72, 85])print(ana.name)print(ana.average())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 also gets a __str__toString method, as "Classes and objects" showed, so that printing a student prints Ana: 78.5 instead of a line of letters and numbers that means nothing to a reader. It joins the name, a colon, and the average.
A list of students
load changes by one line: instead of adding a key to a dictionary, it makes a Student from the name and the marks and adds it to a list. A list keeps the file's order, Ana then Ben then Cy, which the report wants. A dictionary in Python keeps that order too.A HashMap gave the names back in its own order, as Dictionaries and sets warned.
The functions change where they touch the data
Nothing else about the jobs has changed, so each function changes only on the lines that reached into the dictionary:
| Stage 2 | Stage 3 |
|---|---|
| for name in book:for (String name : book.keySet()) | for s in students:for (Student s : students) |
| average(book[name])average(book.get(name)) | s.average() |
best starts as an empty name, with a best average of -1 | best starts as the first student, students[0]students.get(0) |
| top_studenttopStudent gives back a name | it gives back the Student, and the caller reads .name from it |
Starting from the first student is simpler than the -1 trick: a list has a first item, and the loop compares every student with the best so far, the first one included. With an empty file there is no first student, and students[0]students.get(0) stops the program; stage 2's warning about an empty book still holds.
Stage 3
class Student: def __init__(self, name, marks): self.name = name self.marks = marks
def average(self): return sum(self.marks) / len(self.marks)
def __str__(self): return self.name + ": " + str(self.average())
def load(filename): students = [] with open(filename) as f: lines = f.readlines() for line in lines: try: parts = line.strip().split(",") marks = [int(parts[1]), int(parts[2])] students.append(Student(parts[0], marks)) except ValueError: print("Skipping bad line: " + line.strip()) return students
def top_student(students): best = students[0] for s in students: if s.average() > best.average(): best = s return best
def class_average(students): total = 0 for s in students: total = total + s.average() return total / len(students)
students = load("marks.txt")for s in students: print(s)print("Top student: " + top_student(students).name)print("Class average: " + str(class_average(students)))Ana: 78.5 Ben: 75.0 Cy: 90.0 Top student: Cy Class average: 81.16666666666667
import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;import java.util.ArrayList;import java.util.List;
class Student { String name; List<Integer> marks;
Student(String name, List<Integer> marks) { this.name = name; this.marks = marks; }
double average() { int total = 0; for (int m : marks) { total = total + m; } return (double) total / marks.size(); }
public String toString() { return name + ": " + average(); }}
public class Main { static List<Student> load(String filename) throws IOException { List<Student> students = new ArrayList<>(); List<String> lines = Files.readAllLines(Path.of(filename)); for (String line : lines) { try { String[] parts = line.split(","); List<Integer> marks = List.of(Integer.parseInt(parts[1]), Integer.parseInt(parts[2])); students.add(new Student(parts[0], marks)); } catch (NumberFormatException e) { System.out.println("Skipping bad line: " + line); } } return students; }
static Student topStudent(List<Student> students) { Student best = students.get(0); for (Student s : students) { if (s.average() > best.average()) { best = s; } } return best; }
static double classAverage(List<Student> students) { double total = 0; for (Student s : students) { total = total + s.average(); } return total / students.size(); }
public static void main(String[] args) throws IOException { List<Student> students = load("marks.txt"); for (Student s : students) { System.out.println(s); } System.out.println("Top student: " + topStudent(students).name); System.out.println("Class average: " + classAverage(students)); }}Ana: 78.5 Ben: 75.0 Cy: 90.0 Top student: Cy Class average: 81.16666666666667
The last lines print each student with one print per object, which uses __str__toString, then the top student's name and the class average. The output is the same as stage 2's, which is the check: the data changed shape, and the answers did not.
Add a line print(students[1].marks) before the loop and run it again: Ben's list.
Check yourself
Two students are made. What does the program print?
class Student: def __init__(self, name, marks): self.name = name self.marks = marks
def average(self): return sum(self.marks) / len(self.marks)
ana = Student("Ana", [72, 85])ben = Student("Ben", [90, 60])print(ben.average())print(ana.name)import java.util.List;
class Student { String name; List<Integer> marks;
Student(String name, List<Integer> marks) { this.name = name; this.marks = marks; }
double average() { int total = 0; for (int m : marks) { total = total + m; } return (double) total / marks.size(); }}
public class Main { public static void main(String[] args) { Student ana = new Student("Ana", List.of(72, 85)); Student ben = new Student("Ben", List.of(90, 60)); System.out.println(ben.average()); System.out.println(ana.name); }}Complete the missing line so that the method gives back the average of this student's own marks. The program then prints Ana and 78.5.
class Student: def __init__(self, name, marks): self.name = name self.marks = marks
def average(self): ____________________ # ← give back the average of this student's marks
ana = Student("Ana", [72, 85])print(ana.name)print(ana.average())import java.util.List;
class Student { String name; List<Integer> marks;
Student(String name, List<Integer> marks) { this.name = name; this.marks = marks; }
double average() { int total = 0; for (int m : marks) { total = total + m; } ____________________ // ← give back the average of this student's marks }}
public class Main { public static void main(String[] args) { Student ana = new Student("Ana", List.of(72, 85)); System.out.println(ana.name); System.out.println(ana.average()); }}In stage 2 the top-student loop compared average(book[name])average(book.get(name)) with the best so far. With a list of Student objects, and s the student the loop is on, what takes its place?
Honesty notes
- Write a Student class that holds a name and a list of marks, and give it an average method that uses its own marks.
- Load the file into a list of Student objects, one per good line, in the file's order.
- Change each function only where it touched the data: average(book[name]) becomes s.average(), and the loop goes over the students.
- Let the top-student function give back the Student, and read its name from it.