I'm having some trouble developing an algorithm to determine the minimum of a list of n elements. It's not the case of finding the minimum of an array of length n, that's simple:
min = A[0]
for i in range(1, len(A)):
if min > A[i]: min = A[i]
print min
But my list contains objects:
class Object:
def __init__(self, somelist):
self.classification = somelist[0] # String
self.type = somelist[1] # String
self.first = somelist[2] # Integer
self.last = somelist[3] # Integer
And for the same 'classification | type' objects I have m elements and I want to find the minimum element of the same 'classification | type' by comparing the difference between first and last.
Example:
obj1 = Object(['A', 'x', 4, 17])
obj2 = Object(['A', 'y', 5, 20])
obj3 = Object(['B', 'z', 10, 27])
obj4 = Object(['B', 'z', 2, 15])
obj5 = Object(['B', 'z', 20, 40])
obj6 = Object(['A', 'x', 6, 10])
obj7 = Object(['A', 'x', 2, 9])
list = [obj1, obj2, obj3, obj4, obj5, obj6, obj7]
So I need an algorithm to determine the minimums of the list:
A | x --> Object(['A', 'x', 6, 10])
B | z --> Object(['B', 'z', 2, 15])
A | y --> Object(['A', 'y', 5, 20])
Thanks!
filtered = [obj for obj in lst if obj.classification == 'A' and obj.type = 'x']
min(filtered, key=lambda x: x.last - x.first)
Note: don't name your variable list
: it shadows built-in.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With