Hi all! This is the first wave of practice problems for your upcoming quiz Tuesday, November 10th. These problems are great practice for OOP concepts, including classes, methods, constructors, and more! Please try to attempt these on your own before checking the answer key. Good luck!
The solutions to these problems can be found here:
The video going over these solutions can be found here
Exercise 1: Insta User
In this exercise you will write the classes InstaUser and Admin. These classes will model a simplified version of an instagram account. In this scenario, an InstaUser can only change their password with the help of an Admin. Here are the following properties and specifications for each class.
InstaUser (class)
An InstaUser class has the following properties:
- username (
str) - password (
str) - followers (
List[str]) - following (
List[str])
You should initialize all of these properites in the constructor (it is especially important you set the Lists as [] inside the constructor so all the accounts don’t reference the same object on the heap!)
The InstaUser class has the following methods:
getFollowerCount -> returns an
intrepresenting # of followersgetFollowingCount -> return an
intrepresenting # of accounts the user is followinggetMutuals -> return a
List[str]with all the usernames of accounts that a) follow this user account and b) are also followed by this user account (aka they follow each other). Tip: make use of indexes and try/except to check for these mutualsaddFollower -> return
None; this method accepts anInstaUserobject calledperson. It addsperson’s username to the current object’sfollowersList.removeFollower -> return
None; this method accepts anInstaUserobject calledperson. It removesperson’s username from the current object’sfollowersList, if it exists on the List (use theinoperator here!)follow -> return
None; this method accepts anInstaUserobject calledperson. It addsperson’s username to the current object’sfollowingList and adds the current object’s username toperson’sfollowersList usingperson’saddFollowermethod.unfollow -> return
None; this method accepts anInstaUserobject calledperson. It removesperson’s username from the current object’sfollowingList and removes the current object’s username fromperson’sfollowersList usingperson’sremoveFollowermethod.changePassword -> return
bool; this method accepts anAdminobject calledadminand astrcalledpassword. It callsadmin’s method,changePasswordby passing a reference toself(the current object) and the stringpassword. It returns the result ofadmin’schangePasswordmethod, which should be eitherTrueorFalse.
Hint! You will need the following import statment at the top of your file.
The first import statement is most likely unfamiliar. The purpose of this statement is to allow the use of a class as a type inside of itself.
Admin (class)
An Admin class has the following properties:
- username (
str)
You should initialize this properity in the constructor.
The Admin class has the following method:
- changePassword -> returns an
bool; it accepts anInstaUserobject calleduserand astrcallednewPassword. This method should returnFalseif:newPasswordis the same asuser’s current password. Print the following string: “Error: Password must be new”newPasswordis empty or longer than 12 characters. Print the following string: “Error: Password length out of bounds”
Otherwise, this method should change user’s password to newPassword and return True.
Exercise 2: Classception
What better way to learn about classes in Python than to work with real classes! In this exercise, you will model the course registration period by creating a Student class with methods that give a Student the capability of adding/dropping courses as well as a method to compare schedules with another Student.
- Write a class with the following specifications:
- Each
Studentshould have astrattribute calledname, aDict[str, str]calledschedule, anintattribute calledcredit_hours, and aboolattribute calledfull_time. - Your
Studentclass should have a constructor that takes innameandfull_time. The constructor should use these arguments to initialize thenameandfull_timeattributes. Your constructor should also initialize thescheduleattribute to be an empty dictionary and thecredit_hoursattribute to be0. - Your class should also have 3 methods:
add_course,drop_course, andis_classmate. The functionality of these methods should be as described below in theRequirementssection.
- Each
- Use the
__name__is"__main__"idiom to test the implementation of your function with some sample calls to it whose return values are printed (documentation:https://docs.python.org/3/library/__main__.html).
Requirements
add_course:add_courseshould take 2strvalues and anintvalue as its arguments and returnNone.- The first string will be a course code (ex:
"COMP110"), the second string will be the time that the course starts (ex:"4:45PM"), and the integer will be the number of credit hours that the course is worth. add_courseshould add the course to thescheduleattribute as long as certain conditions are met. Thescheduleattribute is aDict[str, str]that has course codes as its keys and the corresponding start time of the course as its values (ex:{"COMP110": "4:45PM", "COMP211": "12:00PM"}). If the course is successfully added, then thecredit_hourattribute should be increased by the number of credit hours that the added course is worth.- There are several cases that need to be considered, each with a different outcome:
- If the
full_timeattribute isTrue, then the student may not exceed 18 credit hours worth of classes. So, if adding the course will make thecredit_hoursattribute greater than 18, the course cannot be added and you should print the messageAdd unsuccessful: too many credit hours. If adding the course does not make thecredit_hoursattribute exceed 18, then the course can be successfully added. If the course is already in the schedule, simply modify the start time of that course. Otherwise, add the course to the schedule (make the course a key in the schedule dictionary and make the course’s start time its corresponding value in the dictionary). - If the
full_timeattribute isFalse, then the student is a part-time student and may not exceed 8 credit hours worth of classes. So, if adding the course will make thecredit_hoursattribute greater than 8, the course cannot be added and you should print the messageAdd unsuccessful: too many credit hours. If adding the course does not make thecredit_hoursattribute exceed 8, then the course can be successfully added. If the course is already in the schedule, simply modify the start time of that course. Otherwise, add the course to the schedule. - Make sure
add_courseis fully functional before moving on to the other methods since the grader uses youradd_coursemethod to constructStudentobjects when testing the other methods.
drop_course:drop_courseshould take astrvalue and anintvalue as its arguments and returnNone.- The string will be a course code and the integer will be the number of credit hours that the course is worth.
drop_courseshould drop the course from thescheduleattribute as long as certain conditions are met. If the course is successfully dropped, then thecredit_hourattribute should be decreased by the number of credit hours that the dropped course is worth.- There are several cases that need to be considered, each with a different outcome:
- If the
full_timeattribute isTrue, then the student may not take fewer than 12 credit hours worth of classes. So, if dropping the course will make thecredit_hoursattribute less than 12, the course cannot be dropped and you should print the messageDrop unsuccessful: must take at least 12 credit hours to maintain full time status. If dropping the course does not make thecredit_hoursattribute less than 12, then the course can be successfully dropped. If the course is already in the schedule, use the pop operation to remove the course from theschedule. Otherwise, if the course wasn’t in the schedule to begin with, no modifications should be made. - If the
full_timeattribute isFalse, then the student is a part-time student and must be taking at least 1 course. So, if dropping the course will make thecredit_hoursattribute equal to 0, the course cannot be dropped and you should print the messageDrop unsuccessful: must be enrolled in a class to maintain student status. If dropping the course does not make thecredit_hoursattribute equal to 0, then the course can be successfully dropped. If the course is already in the schedule, use the pop operation to remove the course from theschedule. Otherwise, if the course wasn’t in the schedule to begin with, no modifications should be made.
is_classmate:is_classmateshould take aStudentvalue as its only argument and returnbool.is_classmateshould look through both student’sscheduleattribute and create a list that stores all of the common courses that the students are in at the same time- There are 2 cases that need to be considered, each with a different outcome:
- If there are no courses that the students are in at the same time, you should print
"Hi <name attribute of the other student>, my name is <name attribute of self>!on one line, then print"Unfortunately, we have no classes together"on the next line, and then returnFalse. See below for example:
>>> from exercises.ex<TBD> import * >>> name1 = "Marlee" >>> full_time1 = False >>> student1 = Student(name1, full_time1) >>> student1.add_course("COMP110", "4:45PM", 3) >>> name2 = "Marc" >>> full_time2 = True >>> student2 = Student(name2, full_time2) >>> student2.add_course("COMP110", "8:00AM", 3) >>> student1.is_classmate(student2) Hi Marc, my name is Marlee! Unfortunately, we have no classes together FalseIf the students are in any of the same courses at the same time, you should print
"Hi <name attribute of the other student>, my name is <name attribute of self>!on one line, then print"This is a list of classes that I have with you: <list of common_classes>"on the next line, and then returnTrue. See below for example:>>> from exercises.ex<TBD> import * >>> name1 = "Marlee" >>> full_time1 = False >>> student1 = Student(name1, full_time1) >>> student1.add_course("COMP110", "4:45PM", 3) >>> name2 = "Marc" >>> full_time2 = True >>> student2 = Student(name2, full_time2) >>> student2.add_course("COMP110", "4:45PM", 3) >>> student1.is_classmate(student2) Hi Marc, my name is Marlee! This is a list of classes that I have with you: ['COMP110'] True- To gain full credit for these print statements, you may not use concatenation. Instead, you must make use of f-strings.
Use correct static type annotations for function’s parameters and return type.