checkio min and max

自己写的代码和下面这个思路很像,但是测试没通过。iter和next没用到。用的是赋值比较。然后有个编程的思想就是never repeat yourself。显然这个代码做的不够好。但是由于是对应的函数所以也没什么关系。

def min(*args, **kwargs):
    key = kwargs.get("key", lambda x: x)
    length = len(args)
    if length == 1:
        values = args[0]
    else:
        values = args
    min_value = next(iter(values))
    for value in values:
        if key(value) < key(min_value):
            min_value = value
    return min_value
​
def max(*args, **kwargs):
    key = kwargs.get("key", lambda x: x)
    length = len(args)
    if length == 1:
        values = args[0]
    else:
        values = args
    max_value = next(iter(values))
    for value in values:
        if key(value) > key(max_value):
            max_value = value
    return max_value

上面的args和kwargs是关键字参数。修改下函数参数就能简单。用sorted的思路。sorted函数是个好东西。

def get_first_from_sorted(args, key, reverse):
    if len(args) == 1:
        args = iter(args[0])
    return sorted(args, key=key, reverse=reverse)[0]

def min(*args, key=None):
    return get_first_from_sorted(args, key, False)

def max(*args, key=None):
    return get_first_from_sorted(args, key, True)

这里写链接内容
sorted(iterable[, cmp[, key[, reverse]]])
Return a new sorted list from the items in iterable.

The optional arguments cmp, key, and reverse have the same meaning as those for the list.sort() method (described in section Mutable Sequence Types).

cmp specifies a custom comparison function of two arguments (iterable elements) which should return a negative, zero or positive number depending on whether the first argument is considered smaller than, equal to, or larger than the second argument: cmp=lambda x,y: cmp(x.lower(), y.lower()). The default value is None.

key specifies a function of one argument that is used to extract a comparison key from each list element: key=str.lower. The default value is None (compare the elements directly).

reverse is a boolean value. If set to True, then the list elements are sorted as if each comparison were reversed.

In general, the key and reverse conversion processes are much faster than specifying an equivalent cmp function. This is because cmp is called multiple times for each list element while key and reverse touch each element only once. Use functools.cmp_to_key() to convert an old-style cmp function to a key function.

The built-in sorted() function is guaranteed to be stable. A sort is stable if it guarantees not to change the relative order of elements that compare equal — this is helpful for sorting in multiple passes (for example, sort by department, then by salary grade).

你可能感兴趣的:(checkio min and max)