用于自定义类的Python的Min()(二进制搜索树)

时间:2016-05-12 13:24:34

标签: python python-3.x

我正在实现二进制搜索树并创建了一个最小方法。我想知道如何(或者如果)我可以使它兼容,以便我能够做到:

min(my_tree)

而不是

my_tree.minimum()

我在想它是否使用迭代器,它将是O(N)时间而不是O(lgN)。

2 个答案:

答案 0 :(得分:4)

CPython中min的实现可以在这里找到here。相关代码将在下面重复。

static PyObject *
min_max(PyObject *args, PyObject *kwds, int op)
{
    /* omitted code */
    it = PyObject_GetIter(v);
    /* omitted code */

    maxitem = NULL; /* the result */
    maxval = NULL;  /* the value associated with the result */
    while (( item = PyIter_Next(it) )) {
        /* get the value from the key function */
        if (keyfunc != NULL) {
            val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL);
            if (val == NULL)
                goto Fail_it_item;
        }
        /* no key function; the value is the item */
        else {
            val = item;
            Py_INCREF(val);
        }

        /* maximum value and item are unset; set them */
        if (maxval == NULL) {
            maxitem = item;
            maxval = val;
        }
    /* more omitted code */
    }
}

static PyObject *
builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
{
    return min_max(args, kwds, Py_LT);
}

由此可以看出,无论如何,使用min将是O(n);它遍历iterable中的每个成员。您无法覆盖此行为,我认为您当前对tree.minimum()的使用根本不自然。

答案 1 :(得分:1)

可以编写一个名为min的自己的函数,并使用它来隐藏它实际上不可能的事实:

min_ = min
def min(*args, **kwargs):
    if isinstance(args[0], MyTree):
        return args[0].minimum()
    else:
        return min_(*args, **kwargs)

不要这样做。

相关问题