
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)
Demo
Write a WorldTime class that inherits from the previously defined MyTime class. The WorldTime class should take an additional parameter during initialization to specify whether the time should be displayed in 12-hour or 24-hour format. This additional parameter should be passed as a string '12' or '24'.
Override __str__ so that it returns the time in the selected format.
Implement the + operator for two WorldTime objects. It should return a new WorldTime object representing the sum of their hours and minutes, with minute and hour overflow handled correctly. The resulting time should have the same display format as the first WorldTime object in the addition.
The code cell below shows the expected behavior.
>>> my_24_time = WorldTime(11, 15, '24')
>>> my_12_time = WorldTime(11, 59, '12')
>>> my_24_time.increment_minutes(50)
>>> str(my_24_time)
'12:05'
>>> str(my_12_time)
'11:59 AM'
>>> str(my_12_time + my_24_time)
'12:04 AM'
>>>
>>> my_12_time.increment_minutes(5)
>>> str(my_12_time)
'12:04 PM'
>>> my_12_time.increment_minutes(58)
>>> str(my_12_time)
'1:02 PM'
>>> my_12_time.increment_hours(10)
>>> str(my_12_time)
'11:02 PM'
>>> my_12_time.increment_minutes(59)
>>> str(my_12_time)
'12:01 AM'
>>> my_12_time.increment_hours(25)
>>> str(my_12_time)
'1:01 AM'
The class requirements are:
my_time.py
WorldTime(MyTime)
A class to represent time in 12- or 24-hour format.
__init__(hours, minutes, clock_type)
Initialize a WorldTime object.
Parameters:
|
|
The hour value (0 to 23). |
|
|
The minute value (0 to 59). |
|
|
The type of clock, either ‘12’ or ‘24’. |
__str__()
Return a string representing the time.
Returns:
|
The time in the specified clock format. |
__add__(other)
Add two WorldTime objects. The resulting time is based on the first object’s clock type.
Parameters:
|
|
Another WorldTime object to add. |
Returns:
|
A new WorldTime object representing the sum. |
Use the following script to check your class test_world_time.py. If your class fails the test in this script, it would also fail if you could hand it in.
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.
Check
For now, your code should work similarly to the example below.
>>> scores = ScoreTracker()
>>> scores.include(105, 'Alice')
>>> print(scores)
HIGH SCORES
Winner 105 Alice
Runner up 0
>>> scores.include(98, 'Bob')
>>> print(scores)
HIGH SCORES
Winner 98 Bob
Runner up 105 Alice
>>> scores.include(108, 'Alice')
>>> print(scores)
HIGH SCORES
Winner 108 Alice
Runner up 98 Bob
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.
Check
Now, your code should work similarly to the example below.
>>> scores = ScoreTracker()
>>> scores.include(105, 'Alice')
>>> scores.include(98, 'Bob')
>>> scores.include(108, 'Alice')
>>> scores.include(106, 'Charlie')
>>> print(scores)
HIGH SCORES
Winner 108 Alice
Runner up 106 Charlie
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
ScoreTrackerobject.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
includeshould take care of keeping track of the two highest scores.Return the new object.
Check
Now, your code should work similarly to the example below.
>>> wednesday_scores = ScoreTracker()
>>> wednesday_scores.include(105, 'Alice')
>>> wednesday_scores.include(98, 'Bob')
>>> print('\nWEDNESDAY', wednesday_scores)
WEDNESDAY HIGH SCORES
Winner 105 Alice
Runner up 98 Bob
>>>
>>> thursday_scores = ScoreTracker()
>>> thursday_scores.include(102, 'Charlie')
>>> thursday_scores.include(99, 'Alice')
>>> print('\nTHURSDAY', thursday_scores)
THURSDAY HIGH SCORES
Winner 102 Charlie
Runner up 99 Alice
>>>
>>> combined_scores = wednesday_scores + thursday_scores
>>> print('\nCOMBINED', combined_scores)
COMBINED HIGH SCORES
Winner 105 Alice
Runner up 102 Charlie
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
Check
The new class should work similarly to the example below.
>>> scores = UniqueScoreTracker()
>>> scores.include(105, 'Alice')
>>> scores.include(98, 'Bob')
>>> scores.include(108, 'Alice')
>>> print(scores)
HIGH SCORES
Winner 108 Alice
Runner up 98 Bob
>>> scores.include(99, 'Alice')
>>> print(scores)
HIGH SCORES
Winner 108 Alice
Runner up 98 Bob
>>> scores.include(109, 'Bob')
>>> print(scores)
HIGH SCORES
Winner 109 Bob
Runner up 108 Alice
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?
Answer
The problem is that the __add__ method in the ScoreTracker class uses ScoreTracker() to create a new object (at least if you followed our hints). This means that the UniqueScoreTracker class inherits a method which creates a ScoreTracker object. A solution would be to override the __add__ method in the UniqueScoreTracker class.
For a slightly more advanced solution, check Advanced 11.2: Smart Object Creation.
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.
Hint
To simplify a fraction, say \(a/b\), you need to find a greatest common divisor of \(a\) and \(b\). One way to find this number is to loop through the integers from 2 up to and including the smaller of \(a\) and \(b\,.\) For each integer, check whether it divides both \(a\) and \(b\). Keep track of the largest integer that does. Then, you can divide both the numerator and denominator by that number to simplify the fraction. If there is no integer that divides both \(a\) and \(b\), the fraction is already in its simplest form.
For example, for \(12/18\), you would loop through the integers 2, 3, 4, …, 12. The largest integer that divides both 12 and 18 is 6. Therefore, you would divide both the numerator and denominator by 6 to get the simplified fraction \(2/3\).
Hint
To check whether two fractions \(\frac{a}{b}\) and \(\frac{c}{d}\) are equal, you can cross-multiply. Calculate \(a \cdot d\) and \(b \cdot c\,.\) If the two products are equal, the fractions are equal; otherwise, they are not.
For example, \(\frac{2}{3}\) and \(\frac{4}{6}\) are equal because \(2 \cdot 6 = 3 \cdot 4\).
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:
|
|
The positive numerator of the fraction. |
|
|
The positive denominator of the fraction. |
__str__()
Return the fraction in numerator/denominator form.
Returns:
|
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:
|
|
The fraction to compare with. |
Returns:
|
True if the fractions have the same value, otherwise False. |
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:
|
|
The total number of questions. |
record_answer(question_num, answer)
Record an answer for a specific question.
Parameters:
|
|
The question number (1-indexed). |
|
|
The answer given by the student. |
get_answer(question_num)
Return the recorded answer for a specific question.
Parameters:
|
|
The question number (1-indexed). |
Returns:
|
The recorded answer, or None if the question has not been answered. |
completion_percentage()
Calculate the percentage of questions answered.
Returns:
|
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:
|
|
The total number of questions. |
|
|
The number of attempts allowed per question. |
record_answer(question_num, answer)
Record an answer, respecting the attempt limit.
Parameters:
|
|
The question number (1-indexed). |
|
|
The answer given by the student. |
Solutions to Demo Tasks
Solution to Demo 11.1: World Time
class WorldTime(MyTime):
def __init__(self, hours, minutes, clock_type):
self.clock_type = clock_type
super().__init__(hours, minutes)
def __str__(self):
if self.clock_type == '24':
return f"{self.hours:02}:{self.minutes:02}"
if self.hours >= 12:
ampm = 'PM'
else:
ampm = 'AM'
h = self.hours
if h > 12:
h = h - 12
if h == 0:
h = 12
return f"{h}:{self.minutes:02} {ampm}"
def __add__(self, other):
added = WorldTime(self.hours, self.minutes, self.clock_type)
added.increment_minutes(other.minutes)
added.increment_hours(other.hours)
return added