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!
group_funcreturns a tuple key containing the object’s classification, then type (e.g.('A', 'x')). This is first used to sort the listl(sortedcall). We then callgroupbyon the sorted list, usinggroup_functo group into sublists. Every time the key changes, we have a new sublist. Unlike SQL, groupby requires the list be pre-sorted on the same key.maptakes the output of thegroupbyfunction. For each group,mapreturns a tuple. The first element ispair[0], which is the key('A', 'x'). The second is the minimum of the group (pair[1]), as determined by thelast - firstkey.