Problem: Given a list of objects, find the minimum and maximum value based on the class property in Python.
For Example, from a list of cars and find out which car has will come first and last in terms of their max speed.
To do this, we have to:
- Declare a class named
max_speedas one of its properties.
- Create a list of objects.
- Find the minimum and maximum of the objects on the basis of the
max_speedproperty using the Python min() and max() methods.
#create class class Car: def __init__(self, max_speed): self.name = name self.max_speed = max_speed #create list of objects cars_list = [Car('Nano', 258), Car('Ferrari', 337), Car('Maruti', 501)] #use max() method to find car with max speed first = max(cars_list, key=lambda car: car.max_speed) #use min() method to find car with min speed last = min(cars_list, key=lambda car: car.max_speed) #output the results print('Car with Maximum Speed: ',first.name) print('Car with Minimum Speed: ',last.name)
Car with Maximum Speed: Maruti
Car with Minimum Speed: Nano