I have a code where I need to remove an entry of a person from a school roster. At the very bottom of the code, I have the parameter of Stern, the final print statement prints the roster without Stern. I don't know how to remove the person from the list since there is a first name and a last name, and I am not allowed to put both first names and last name as a parameter. I don't really know if I can use the .pop() or .remove() in this case. Can I just remove the name by removing the index from the list? Ive also tried delattr
class Student:
def __init__(self, first, last, gpa):
self.first = first # first name
self.last = last # last name
self.gpa = gpa # grade point average
def get_gpa(self):
return self.gpa
def get_last(self):
return self.last
def to_string(self):
return self.first ' ' self.last ' (GPA: ' str(self.gpa) ')'
class Course:
def __init__(self):
self.roster = [] # list of Student objects
**def drop_student(self, student):
#space where i remove one student**
def add_student(self, student):
self.roster.append(student)
def count_students(self):
return len(self.roster)
if __name__ == "__main__":
course = Course()
course.add_student(Student('Henry', 'Nguyen', 3.5))
course.add_student(Student('Brenda', 'Stern', 2.0))
course.add_student(Student('Lynda', 'Robinson', 3.2))
course.add_student(Student('Sonya', 'King', 3.9))
print('Course size:', course.count_students(),'students')
course.drop_student('Stern')
print('Course size after drop:', course.count_students(),'students')
CodePudding user response:
My solution would be using remove
. But you will have to grab the student first (e.g. by filtering/searching the list).
def drop_student(self, first, last):
matches = list(filter(lambda student: student.first == first and student.last == last, self.roster))
if len(matches) > 1:
raise Exception("Student not unique")
elif len(matches) < 1:
print(f"No student named {first} {last}")
else:
self.roster.remove(matches[0])
CodePudding user response:
In the end of your code
course.dropstudent('Stren')
Can't be called because in your property definition you pass "Student" object as a parameter so when you call your property you can't call it with a 'String'.
Use instead
Stud_Stren = Student('Brenda', 'Stern', 2.0)
course.dropstudent(Stud_Stren)
And take the code that Lukas Schmid had given to you for your "drop_student" property and give it some modification to use the attribute of your student object (First name, last name, gpa), Or take it as it is if you don't want to pass a student object and replace your call by
course.dropstudent('Brenda', 'Stern')