def minimal(iterable, func):
    """Return a list of minimal values according to a weighting function"""
it = iter(iterable)
try:
    x = next(it)
except StopIteration:
    return []
lowest_values = [x]
lowest_weight = func(x)
for x in it:
    weight = func(x)
if weight == lowest_weight:
    lowest_values.append(x)
elif weight < lowest_weight:
    lowest_values = []
lowest_weight = weight
return lowest_values
Find all minimal elements in a list or set as weighted by a function