Week 11: Classes II

Week 11: In-Class#

Demo#

Demo 11.1: World Time#

The class we implemented in Demo 10.1: My Time may be improved by adding the ability to represent time in 24-hour format or 12-hour format. For both formats, we want to be able to display the time appropriately.

In 24-hour format, the time is displayed as HH:MM, where HH represents the hour (00 to 23) and MM the minute (00 to 59). In 12-hour format, the time is displayed as H:MM AM/PM, where H represents the hour (1 to 12), MM the minute (00 to 59), and AM or PM indicates whether it is before noon or after noon that day. Noon is written as 12:00 PM, and midnight as 12:00 AM.

If an event starts at a certain time and lasts for a certain duration, we would like to be able to calculate the end time. Therefore, we would like to be able to add two times together. The addition should correctly carry extra minutes into the hours and wrap around after midnight.

Problem Analysis

How should times given as (hours, minutes) tuples be displayed in both 24-hour and 12-hour formats? Consider the following cases:

  • (0, 15)

  • (12, 0)

  • (16, 14)

  • (23, 59)

What happens when we add two times given as (hours, minutes) together? Consider the following cases:

  • (11, 15) and (1, 50)

  • (19, 30) and (5, 30)

Coding Practice#

Code 11.2: Check NumPy and Matplotlib#

Next week is about NumPy and Matplotlib. It is important to that you verify that they work on your computer before next week, by running the following code:

import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 2*np.pi, 100)
plt.plot(np.cos(x), np.sin(x))
plt.show()

If this displays an oval on the screen, then NumPy and Matplotlib are working correctly. If you get an error, visit Python Support before doing next week’s Copy-and-Run exercises.

Code 11.3: Score Tracker#

You need a class which keeps track of the scores of a game. You want only the two highest scores to be stored, together with the names of the players who achieved them. When initialized, the class should be empty, and the scores should be included one by one.

Let’s make a class ScoreTracker step by step.

First, consider what the class should have as attributes. You need to keep track of four things: the highest score, the second highest score, the name of the player who achieved the highest score, and the name of the player who achieved the second highest score. Deciding on which attributes to use is a programmer’s task: it can be 4 separate attributes, or a 2-element list (or tuple) for scores and a 2-element list for names, or a dictionary. You can choose any suitable representation, but we will assume that you have attributes score_1, score_2, name_1, and name_2.

Write code where you define the class ScoreTracker. The constructor should initialize the attributes score_1 and score_2 to 0 and the attributes name_1 and name_2 to an empty string.

Write the code for the method include which takes as input the score of the player and the name of the player. For now, this method should always do the same: move the player who is currently first to second place, and replace the first player with the new player. We will later modify this method to keep track of the two highest scores.

Write the code for the method __str__ such that it returns a nice string representation of the object. It is up to you how you want to represent the object as a string; you can take inspiration from the examples below.

Let’s now modify the include method to keep track of the two highest scores. Notice that there are two situations where the score needs to be updated:

  • When the new score is higher than or equal to the highest score.

  • When the new score is higher than or equal to the second highest score but lower than the highest score.

Write an if - elif statement to handle these two cases.

In the first case, you should do the same as before: move the first player to the second place and replace the first player with the new player. In the second case, you should only replace the second player with the new player.

Finally, you want to be able to combine several ScoreTracker objects and get the overall highest scores. Let’s overload the + operator to combine two ScoreTracker objects. The result should be a new ScoreTracker object, which keeps track of the highest scores of the two input objects.

You need to define the __add__ method in the class ScoreTracker. This method should take another ScoreTracker object as input and return a new ScoreTracker object. Notice that you can use the methods you have already defined in the class to achieve this.

  • First, create a new ScoreTracker object.

  • Include four players in the new object: the two players from the first object and the two players from the second object. Your implementation of include should take care of keeping track of the two highest scores.

  • Return the new object.

Code 11.4: Unique Score Tracker#

The score tracker you have implemented in the previous task may end up having the same player in both the first and the second place. This is not very interesting, so you want to modify the class to keep track of unique players. That is, the tracker should still keep track of the two highest scores, but if the same player achieves both scores, the player should be listed only as the winner, and the second place should be given to another player.

Instead of modifying the ScoreTracker class, you will create a new class UniqueScoreTracker which inherits from ScoreTracker. Notice that the only difference between the two classes is the include method, which needs to include the check for unique players.

You can include name checks before or after the score checks. One way where name checks happen after score checks is sketched below.

if score is larger than or equal to the highest score:
    if name is already the winner:
        Update the score of the winner
    else:
        Include the new result as the winner, move the current winner to runner-up  
elif score is larger than or equal to the runner-up score:
    if name is not the winner:
        Include the new score as runner-up 

Test whether you can combine two UniqueScoreTracker objects using the + operator. This should work without error because the UniqueScoreTracker class inherits the __add__ method from the ScoreTracker class. However, if you test thoroughly, you will notice that the combined score may contain the same player in both the first and the second place. To figure out how this is possible, try to print the type of the combined score. Where in the code do you define the object which is returned by the __add__ method? Why is this a problem?

Problem Solving#

Problem 11.5: Fractions#

Create a class to represent fractions whose numerators and denominators are positive integers. The constructor should take the numerator and denominator as arguments and store them as attributes.

The fraction’s string representation should have the form numerator/denominator. For example, a fraction with numerator 3 and denominator 7 should be represented as 3/7.

Implement a simplify() method that reduces the fraction to its simplest form. For example, simplifying 12/16 should result in 3/4.

Also, implement the == operator to compare two fractions. Two fractions are equal if they have the same value. Comparing fractions should not modify either object.

Here is an example of using the class.

>>> first = Fraction(12, 16)
>>> second = Fraction(3, 4)
>>> str(first)
'12/16'
>>> first == second
True
>>> str(first)
'12/16'
>>> str(second)
'3/4'
>>> first == Fraction(1, 2)
False
>>> first.simplify()
>>> str(first)
'3/4'

The filename and requirements are in the box below:

fraction.py

Fraction

A fraction with a positive integer numerator and denominator.

__init__(numerator, denominator)

Initialize a fraction with the given numerator and denominator.

Parameters:

  • numerator

int

The positive numerator of the fraction.

  • denominator

int

The positive denominator of the fraction.

__str__()

Return the fraction in numerator/denominator form.

Returns:

  • str

The numerator and denominator separated by a slash.

simplify()

Reduce the fraction in place to its simplest form.

__eq__(other)

Compare fractions without modifying either object.

Parameters:

  • other

Fraction

The fraction to compare with.

Returns:

  • bool

True if the fractions have the same value, otherwise False.

Problem 11.6: Authors#

Create a class that represents an ordered list of authors. The constructor should take the first and last names of the first author. Implement an add_author method that takes a first name and a last name and adds the author to the end of the list.

Implement a get_authors method that returns a string containing each author’s first and last name in the order they were added. For one author, return the full name, for example Anna Adams. For two authors, join their names with and, for example Anna Adams and Bob Brown. For three or more authors, separate the names with commas and add and before the last name, for example Anna Adams, Bob Brown, and Charlie Clark.

The string representation of the object should use only the authors’ last names. For one author, return the last name, for example Adams. For two authors, join their last names with and, for example Adams and Brown. For three or more authors, return the first author’s last name followed by et al., for example Adams et al..

Here is an example of using the class.

>>> authors = Authors('Anna', 'Adams')
>>> authors.get_authors()
'Anna Adams'
>>> str(authors)
'Adams'
>>> authors.add_author('Bob', 'Brown')
>>> authors.get_authors()
'Anna Adams and Bob Brown'
>>> str(authors)
'Adams and Brown'
>>> authors.add_author('Charlie', 'Clark')
>>> authors.get_authors()
'Anna Adams, Bob Brown, and Charlie Clark'
>>> str(authors)
'Adams et al.'
>>> authors.add_author('Dana', 'Davis')
>>> authors.get_authors()
'Anna Adams, Bob Brown, Charlie Clark, and Dana Davis'
>>> str(authors)
'Adams et al.'

The filename and requirements are in the box below:

authors.py

Authors

An ordered list of authors.

__init__(first_name, last_name)

Initialize the list with its first author.

Parameters:

  • first_name

str

The first author’s first name.

  • last_name

str

The first author’s last name.

add_author(first_name, last_name)

Add an author to the end of the list.

Parameters:

  • first_name

str

The author’s first name.

  • last_name

str

The author’s last name.

get_authors()

Return the authors’ full names in the order they were added.

Returns:

  • str

The full names as an English list with an Oxford comma, e.g. ‘A and B’ or ‘A, B, and C’.

__str__()

Return the authors’ last names in citation form.

Returns:

  • str

One last name, two last names joined by ‘and’, or the first followed by ‘et al.’.

Problem 11.7: Multiple Choice#

Create a class MultipleChoice to manage a student’s answers to a multiple-choice test.

The constructor should take the number of questions. Implement a record_answer method to store the student’s answers. The method should take the question number and the answer as input. Implement a get_answer method that takes the question number as input and returns the recorded answer, or None if the question has not been answered. Implement a completion_percentage method that returns the percentage of questions that have been answered.

Here is an example of using the class.

>>> mc = MultipleChoice(10)
>>> mc.record_answer(1, 'B')
>>> mc.record_answer(2, 'A')
>>> mc.get_answer(2)
'A'
>>> mc.completion_percentage()
20.0

The filename and requirements are in the box below:

multiple_choice.py

MultipleChoice

Manages student answers to a multiple-choice test.

__init__(num_questions)

Initialize a MultipleChoice test.

Parameters:

  • num_questions

int

The total number of questions.

record_answer(question_num, answer)

Record an answer for a specific question.

Parameters:

  • question_num

int

The question number (1-indexed).

  • answer

str

The answer given by the student.

get_answer(question_num)

Return the recorded answer for a specific question.

Parameters:

  • question_num

int

The question number (1-indexed).

Returns:

  • str

The recorded answer, or None if the question has not been answered.

completion_percentage()

Calculate the percentage of questions answered.

Returns:

  • float

The completion percentage (0-100).

Problem 11.8: Multiple Choice Restricted#

Create a class MultipleChoiceRestricted that extends MultipleChoice. This class restricts how many times a student can change their answer to a question.

The constructor should take the number of questions and the number of allowed attempts per question. For example, if the number of allowed attempts is 2, then the student may answer each question at most 2 times. The record_answer method should still store the student’s answers, but if the student has already used all their attempts for that question, nothing happens (the method simply ends without recording the answer). The completion_percentage method should work the same way as in the parent class.

Here is an example of using the class.

>>> mcr = MultipleChoiceRestricted(5, 2)
>>> mcr.record_answer(1, 'A')
>>> mcr.record_answer(1, 'B')
>>> mcr.record_answer(1, 'C')
>>> mcr.get_answer(1)
'B'

The filename and requirements are in the box below:

multiple_choice.py

MultipleChoiceRestricted(MultipleChoice)

A multiple-choice test with limited attempts per question.

__init__(num_questions, attempts)

Initialize a restricted multiple-choice test.

Parameters:

  • num_questions

int

The total number of questions.

  • attempts

int

The number of attempts allowed per question.

record_answer(question_num, answer)

Record an answer, respecting the attempt limit.

Parameters:

  • question_num

int

The question number (1-indexed).

  • answer

str

The answer given by the student.

Solutions to Demo Tasks