Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
push the argument handling into one place solution in Clear category for Min and Max by pkshiu
def my_min(a, b, f):
# return min value between a and b, using extraction function f to
# extract actual value from a and b for comparison
return a if f(a) <= f(b) else b
def my_max(a, b, f):
# and max version
return a if f(a) >= f(b) else b
def alg(cmp_func, *args, **kwargs):
# implement the actual algorithm for going thru the inputs and applying
# some comparison function
#
# TODO: handle empty arg case !
# get the extraction function, if not specified, use an identify function
f = kwargs.get("key", lambda x: x)
if len(args) > 1:
# turn into an iterable
items = iter(args)
else:
items = args[0]
v = None
for i in items:
if v is None:
v = i
else:
v = cmp_func(v, i, f)
return v
def min(*args, **kwargs):
return alg(my_min, *args, **kwargs)
def max(*args, **kwargs):
return alg(my_max, *args, **kwargs)
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"
assert min([[1, 2], [3, 4], [9, 0]], key=lambda x: x[1]) == [9, 0], "lambda key"
Oct. 12, 2016