Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Min and Max solution in Clear category for Min and Max by dpkkumar
def min(*args, **kwargs):
# Using efficient O(n) way to get the minimum.
key = kwargs.get("key", None)
if len(args) == 1: # If Iterable is provided, take the first item
args = args[0]
args = list(args) # list is used to handle the iterator inputs
min_index = 0
minimum = key(args[0]) if key else args[0] # Assume first element is minimum
for index, item in enumerate(args):
data = key(item) if key else item # Apply key
if data < minimum:
min_index = index # Store index of minimum value
minimum = data
return args[min_index] # return minimum value
def max(*args, **kwargs):
# Using sorted function. Shorter for humans but expensive for system(O(nlogn).
key = kwargs.get("key", None)
if len(args) == 1: # If Iterable is provided, take the first item
args = args[0]
output = sorted(args, key=key, reverse=True)[0]
return output
if __name__ == '__main__':
#These "asserts" using only for self-checking and not necessary for auto-testing
assert max(3, 2) == 3, "Simple case max"
assert min(3, 2) == 2, "Simple case min"
assert max([1, 2, 0, 3, 4]) == 4, "From a list"
assert min("hello") == "e", "From string"
assert max(2.2, 5.6, 5.9, key=int) == 5.6, "Two maximal items"
assert min([[1, 2], [3, 4], [9, 0]], key=lambda x: x[1]) == [9, 0], "lambda key"
Nov. 30, 2015