I am trying to sort a list of class Shape.the shape class has a method surface() which return an int. How would I sort this list from biggest to smallest surface
The code is this
def sort_list(list_shapes):
'''
for shape in list_shapes:
shape.surface() = int
output = list_shapes sorted by surface size
'''
pass
# for context: Shape Class
class Shape:
def __init__(self, width, height):
self.width = width
self.height = height
def surface(self):
surface = float(self.width * self.height)
return round(surface, 2)
I've tried with sort and sorted but cant seem to make it work. I believe possibly I could do something like list(map()) but also couldn't figure it out.
Would love to get a better understanding on which way is best for this
CodePudding user response:
You can use built-in sorted()
function __ge__()
/ __lt__()
magic methods.
Here is an example:
class Shape:
def __init__(self, width, height):
self.width = width
self.height = height
def __ge__(self, other: 'Shape'):
return self.surface() > other.surface()
def __lt__(self, other: 'Shape'):
return self.surface() < other.surface()
def __repr__(self):
# return surface - just for print() demo
return str(self.surface())
def surface(self):
surface = float(self.width * self.height)
return round(surface, 2)
shapes = [
Shape(2, 2),
Shape(3, 3),
Shape(1, 2),
Shape(1, 1),
Shape(5, 5),
Shape(2, 1),
Shape(1, 1),
Shape(2, 2),
]
print(sorted(shapes)) # [1.0, 1.0, 2.0, 2.0, 4.0, 4.0, 9.0, 25.0]
CodePudding user response:
def sort_list(list_shapes):
return sorted(list_shapes, key = lambda x: x.surface())