gpt4 book ai didi

python - 返回字典 get 方法中的递归

转载 作者:行者123 更新时间:2023-12-01 04:29:11 28 4
gpt4 key购买 nike

使用 MWE。函数 foo 工作正常,bar 则不行,并引发“RuntimeError:超出最大递归深度”异常。有什么提示吗?

def foo(i1, i2):
inverse_map = {"<": ">"}
if i1[1] < i2[0]: return "<"
return inverse_map[foo(i2, i1)]

def bar(i1, i2):
inverse_map = {"<": ">"}
return {
i1[1] < i2[0]: "<"
}.get(True, inverse_map[bar(i2, i1)])

i1, i2 = (0, 2), (4, 6)
print foo(i2, i1), ">"
print bar(i2, i1), ">"

最佳答案

Python字典get方法首先检查默认值,因此,在bar函数中,它会在之前递归调用bar >返回值。您的代码可以转换为以下格式,这会导致死递归:

def foo(i1, i2):
inverse_map = {"<": ">"}
if i1[1] < i2[0]: return "<"
return inverse_map[foo(i2, i1)]

def bar(i1, i2):
inverse_map = {"<": ">"}
d = {i1[1] < i2[0] : "<"}
inverse = inverse_map[bar(i2,i1)]
return d.get(True,inverse)

i1, i2 = (0, 2), (4, 6)
print foo(i1, i2), ">"
print bar(i2, i1), ">"

字典get实现的快照如下所示:

static PyObject *
dict_get(register PyDictObject *mp, PyObject *args)
{
PyObject *key;
PyObject *failobj = Py_None;
PyObject *val = NULL;
long hash;
PyDictEntry *ep;
#commented by myself, get function first check default value
if (!PyArg_UnpackTuple(args, "get", 1, 2, &key, &failobj))
return NULL;

if (!PyString_CheckExact(key) ||
(hash = ((PyStringObject *) key)->ob_shash) == -1) {
hash = PyObject_Hash(key);
if (hash == -1)
return NULL;
}
ep = (mp->ma_lookup)(mp, key, hash);
if (ep == NULL)
return NULL;
val = ep->me_value;
if (val == NULL)
val = failobj;
Py_INCREF(val);
return val;
}

python dictionary implementation

关于python - 返回字典 get 方法中的递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32620769/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com