python - "Balancing"符号列表

标签 python algorithm list python-3.x numpy

考虑一个包含从一组符号中提取元素的列表,例如{A,B,C}:

List             --> A, A, B, B, A, A, A, A, A, B,  C,  C,  B, B
Indexing indices --> 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13

我如何重新排序这个列表,以便对于任何符号,我们在列表的前半部分有大约一半的符号,即 [0, [N/2 ]] 列表的一半和下半部分?即 [[N/2, N]]

请注意,此问题可能有多种解决方案。我们还想计算排列的结果索引列表,以便我们可以将新排序应用于与原始列表关联的任何列表。

这个问题有名字吗?有什么有效的算法吗?我能想到的大多数解决方案都非常暴力。

最佳答案

你可以在这里使用字典,这将花费 O(N) 时间:

from  collections import defaultdict


lst = ['A', 'A', 'B', 'B', 'A', 'A', 'A', 'A', 'A', 'B', ' C', ' C', ' B', 'B']
d = defaultdict(list)
for i, x in enumerate(lst):
    d[x].append(i)

items = []
indices = []
for k, v in d.items():
    n = len(v)//2
    items.extend([k]*n)
    indices.extend(v[:n])

for k, v in d.items():
    n = len(v)//2
    items.extend([k]*(len(v)-n))
    indices.extend(v[n:])

print items
print indices

输出:

['A', 'A', 'A', ' C', 'B', 'B', 'A', 'A', 'A', 'A', ' C', 'B', 'B', ' B']
[0, 1, 4, 10, 2, 3, 5, 6, 7, 8, 11, 9, 13, 12]

关于python - "Balancing"符号列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28949293/

相关文章:

python - 无法从 GAE 本地环境中获取 URL

python - 如何使用 Python post 请求和 Telegram 机器人在 Telegram 上发送具有 InlineKeyboardMarkup 的照片

python - 使用 Python 搜索多个文本文件以匹配字符串列表

algorithm - Disjoint Set Forest 来调度作业

r - 提取列表中数字的范围

list - 合并(合并)不同长度的向量

python - 将文本和图像添加到图像的简单方法(对于 fb 应用程序) - PIL 在依赖性方面是 hell

c++ - 为我的图形数据结构实现 BFS 时出现问题

algorithm - 多项式时间 : Accepting and Decision Algorithms

Python 列表排序