栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

sum二维数组扁平为一维数组

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

sum二维数组扁平为一维数组

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__
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/460767.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号