leetcode LCP39 无人机方阵 python代码解法,自己探索解读下
from typing import List
from collections import Counter
class Solution:
def minimumSwitchingTimes(self, source: List[List[int]], target: List[List[int]]) -> int:
source, target = Counter(sum(source, [])), Counter(sum(target, []))
diff = source - target
return sum(diff.values())
sum将二维数组扁平化为一维数组
// sum实现
// Python-3.8.10Pythonbltinmodule.c简化了源码
static PyObject *
builtin_sum_impl(PyObject *module, PyObject *iterable, PyObject *start)
{
PyObject *result = start;
PyObject *temp, *item, *iter;
iter = PyObject_GetIter(iterable);
if (iter == NULL)
return NULL;
if (result == NULL) {
result = PyLong_FromLong(0);
if (result == NULL) {
return NULL;
}
}
for(;;) {
item = PyIter_Next(iter);
if (item == NULL) {
break;
}
temp = PyNumber_Add(result, item);
result = temp;
if (result == NULL)
break;
}
return result;
}
- sum的逻辑是自然的,将序列的元素一个一个加起来(代码for段落)
- sum有个初始值start,如果不传默认为0PyLong_FromLong(0),所以代码中将初始值设为空列表[],否则报错,0加上列表是错误的
// Python-3.8.10Objects/abstract.c简化了源码
// PyNumber_Add实现
PyObject *
PyNumber_Add(PyObject *v, PyObject *w)
{
PyObject *result = binary_op1(v, w, NB_SLOT(nb_add));
return result;
}
// binary_op1实现
static PyObject *
binary_op1(PyObject *v, PyObject *w, const int op_slot)
{
PyObject *x;
binaryfunc slotv = NULL;
binaryfunc slotw = NULL;
if (v->ob_type->tp_as_number != NULL)
slotv = NB_BINOP(v->ob_type->tp_as_number, op_slot);
if (w->ob_type != v->ob_type &&
w->ob_type->tp_as_number != NULL) {
slotw = NB_BINOP(w->ob_type->tp_as_number, op_slot);
if (slotw == slotv)
slotw = NULL;
}
if (slotv) {
x = slotv(v, w);
if (x != Py_NotImplemented)
return x;
}
if (slotw) {
x = slotw(v, w);
if (x != Py_NotImplemented)
return x;
}
Py_RETURN_NOTIMPLEMENTED;
}
- binary_op1判断参数x, y是否实现了op_slot,对应list就是__add__



