当前位置: 首页 > article >正文

均匀合并列表

1 、背景

给定一个二维列表,均匀合并成一个一维列表,使得列表中原始元素所在位置尽可能均衡。
例如:
[[a, a, a], [b, b]] -> [a, b, a, b, a]

2、思路:

这道题可以按照两两合并的归并思路来做,不过最优的做法还是将元素转化为索引的优先级来通过排序解决。

3、解法:


# 均匀插入,对索引进行优先级建模
def shuffle_merge_indexed(items_list):
    result = []
    max_length = max([len(items) for items in items_list]) + 1
    for items in items_list:
        items_len = len(items)
        result.extend([((i + 1.0) * max_length / (items_len+1), v) for i, v in enumerate(items)])
    result = [i[1] for i in sorted(result, key=lambda x: x[0])]
    return result


# 两两合并
def shuffle_merge_two(items_list):
    def merge(list1, list2):  # 两个列表均匀合并即可
        l1, l2 = len(list1), len(list2)
        if l1 > l2:
            long_list, short_list = list1, list2
        else:
            long_list, short_list = list2, list1
        interval_len = len(long_list) // (len(short_list) + 1)  # 间隔
        last_n = len(long_list) % (len(short_list) + 1)  # 还剩余几个
        intervals = [interval_len for _ in range(len(short_list) + 1)]
        l, r = len(intervals) // 2, (len(intervals) // 2) + (len(intervals) % 2)
        while last_n > 0:
            intervals[l] += 1
            last_n -= 1
            l -= 1
            if intervals[r] == interval_len and last_n > 0:
                intervals[r] += 1
                last_n -= 1
                r += 1
        assert sum(intervals) == len(long_list)
        res = []
        pre_sum = 0
        for i in range(len(short_list)):
            res += long_list[pre_sum: pre_sum + intervals[i]] + [short_list[i]]
            pre_sum += intervals[i]
        res += long_list[pre_sum:]
        assert len(res) == l1 + l2
        return res
    # 两两依次合并
    l = len(items_list)
    merged = items_list[0]
    for _ in range(l - 1):
        merged = merge(merged, items_list[1])
        items_list.pop(0)
        items_list[0] = merged
    return items_list[0]


# 归并 -> 不行,因为并行merge可能会导致不均匀
def shuffle_merge_log2(items_list):
    def merge(list1, list2):  # 两个列表均匀合并即可
        l1, l2 = len(list1), len(list2)
        if l1 > l2:
            long_list, short_list = list1, list2
        else:
            long_list, short_list = list2, list1
        interval_len = len(long_list) // (len(short_list) + 1)  # 间隔
        last_n = len(long_list) % (len(short_list) + 1)  # 还剩余几个
        intervals = [interval_len for _ in range(len(short_list) + 1)]
        l, r = len(intervals) // 2, (len(intervals) // 2) + (len(intervals) % 2)
        while last_n > 0:
            intervals[l] += 1
            last_n -= 1
            l -= 1
            if intervals[r] == interval_len and last_n > 0:
                intervals[r] += 1
                last_n -= 1
                r += 1
        assert sum(intervals) == len(long_list)
        res = []
        pre_sum = 0
        for i in range(len(short_list)):
            res += long_list[pre_sum: pre_sum + intervals[i]] + [short_list[i]]
            pre_sum += intervals[i]
        res += long_list[pre_sum:]
        assert len(res) == l1 + l2
        return res
    # 两两同时合并
    l = len(items_list)
    while l != 1:
        temp = []
        for i in range(0, l, 2):
            if i < l - 1:
                temp.append(merge(items_list[i], items_list[i+1]))
            else:
                temp.append(items_list[i])
        l = len(temp)
        items_list = [eve.copy() for eve in temp]
    return temp[0]


if __name__ == '__main__':
    # test_case = [['a'] * 11, ['b']*7, ['c']*3]
    # test_case = [['a'] * 11, ['b']*6, ['c']*3]
    # test_case = [['k']*40, ['v']*2, ['q']*1, ['w']*3, ['o']*10]
    # test_case = [['k']*40, ['v']*5, ['q']*4, ['w']*3, ['o']*2, ['s']*1]
    test_case = [['s']*1, ['k']*2, ['v']*3, ['q']*4, ['w']*5, ['o']*60]

    res1 = shuffle_merge_indexed(test_case)
    res3 = shuffle_merge_two(test_case)

    print('res1:', res1)
    print('res3:', res3)


http://www.kler.cn/a/322517.html

相关文章:

  • vue实现展示并下载后端返回的图片流
  • oracle19c开机自启动
  • 【蓝桥杯备赛】深秋的苹果
  • 【机器学习】聚类算法原理详解
  • 一些常见网络安全术语
  • 无人机场景 - 目标检测数据集 - 车辆检测数据集下载「包含VOC、COCO、YOLO三种格式」
  • 前端面试题(七)
  • 力扣题解2306
  • 探秘电商平台数据采集:API 接口接入实战演示
  • DERT目标检测—End-to-End Object Detection with Transformers
  • pip配置阿里云、清华和中科大的镜像
  • vue2实现提取字符串数字并修改数字样式(正则表达式)
  • Diameter协议
  • 【HarmonyOS】横向List高度适配
  • 什么是数据库视图(View)?视图和表有何区别?
  • 从0到1,数字媒体产业基地见证每一个创意的诞生与成长
  • Oracle 数据库安装和配置指南
  • 西电雨课堂刷课工具
  • Matlab/simulink低版本打开高版本
  • 2024/9/27 The Limitations of Deep Learning in Adversarial Settings读后感
  • 如何查看服务器是否有raid阵列卡以及raid类型
  • CVE-2024-1112 Resource Hacker 缓冲区溢出分析
  • 防火墙详解(二)通过网页登录配置华为eNSP中USG6000V1防火墙
  • 基于springBoot校园健康驿站管理平台(源码+教程)
  • 如何将很多个pdf拼接在一起?很多种PDF拼接的方法
  • GloVe(全局词向量嵌入)