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).

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值