简体   繁体   English

为什么Python的sum()和min()内置函数要好得多?

[英]Why the Python built-in functions of sum() and min() are much better?

Why the built-in functions of sum() and min() are much better than the simple implementation (comment out in the following) ? 为什么sum()和min()的内置函数比简单的实现要好得多(在下文中进行注释)? How do they improve the performance? 他们如何提高性能?

class Solution(object):
def minMoves(self, nums):
    """
    :type nums: List[int]
    :rtype: int
    """
    '''
    m = sys.maxint
    s = 0
    for i in nums:
        s += i
        if i < m:
            m = i
    '''
    m = min(nums)
    s = sum(nums)
    return s - m * len(nums)

As Tigerhawk mentioned in the comments, most built-in functions were written in C, as can be seen here . 作为Tigerhawk在评论中提到的,大多数内置函数写在C,可以看出这里 I believe what we're looking for starts at line 591 : 我相信我们正在寻找的东西从591行开始:

_sum(PyObject *module, PyObject *args)
{
    PyObject *return_value = NULL;
    PyObject *iterable;
    PyObject *start = NULL;

    if (!PyArg_UnpackTuple(args, "sum",
        1, 2,
        &iterable, &start)) {
        goto exit;
    }
    return_value = builtin_sum_impl(module, iterable, start);

exit:
    return return_value;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM