I want to search through a list of objects for the lowest number present in an attribute of the objects.
This is easy enough using a list comprehension and the min
function. The issue comes when I want to find the index of the object.
class School:
def __init__(self, name, num_pupils, num_classrooms):
self.name = name
self.num_pupils = num_pupils
self.num_classrooms = num_classrooms
def students_per_class(self):
return self.num_pupils / self.num_classrooms
def show_info(self):
print(f"{self.name} has {self.students_per_class():.2f} students per class.")
def string_checker(question):
valid = False
while not valid:
try:
response = str(input(question))
if all(character.isalpha() or character.isspace() for character in response):
valid = True
return response
else:
print("Enter a string containing no numbers of special characters. ")
except ValueError:
print("Enter a string containing no numbers of special characters. ")
def num_checker(question):
valid = False
while not valid:
try:
response = int(input(question))
if (response):
valid = True
return response
else:
print("Enter an integer containing no letters or special characters. ")
except ValueError:
print("Enter an integer containing no letters or special characters. ")
def new_school():
school_name = string_checker("School Name: ")
num_pupils = num_checker("Number of Pupils: ")
num_classrooms = num_checker("Number of Classrooms: ")
return School(school_name, num_pupils, num_classrooms)
if __name__ == "__main__":
schools = []
school = School("Darfield High School", 900, 37)
schools.append(school)
school.show_info()
for i in range(1):
schools.append(new_school())
for school in schools:
school.show_info()
print(min(school.students_per_class() for school in schools))
# This works fine and prints the value of the lowest number
print(schools.index(min(school.students_per_class() for school in schools)))
# This doesn't work as it tries to find the index of the value returned
# from the min function as it should.