概述
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;
}
/* It's tempting to use PyNumber_InPlaceAdd instead of
PyNumber_Add here, to avoid quadratic running time
when doing 'sum(list_of_lists, [])'.
However, this
would produce a change in behaviour: a snippet like
empty = []
sum([[x] for x in range(10)], empty)
would change the value of empty. */
temp = PyNumber_Add(result, item);
result = temp;
if (result == NULL)
break;
}
return result;
}
- sum的逻辑是自然的,将序列的元素一个一个加起来(代码for段落)
- sum有个初始值start,如果不传默认为0
PyLong_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__
最后
以上就是炙热裙子为你收集整理的sum二维数组扁平为一维数组的全部内容,希望文章能够帮你解决sum二维数组扁平为一维数组所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复