我有一个带有{integer_key -> list[tuple]}
键/值对的地图。元组包含(start,end)
表示子字符串操作的字符串索引的值。
我的目标是删除重叠区域并返回键/值对所在的映射{tuple -> integer_key}
。映射到较低的范围integer_keys
优先于较高的范围。
下面是我当前实现的一个可运行示例(需要这个ordereddict类):
from collections import OrderedDict
string_length = 20
idx_region_map = OrderedDict()
idx_region_map[0] = [(0,2), (7,10)]
idx_region_map[1] = [(4,5), (18,19)]
idx_region_map[2] = [(3,3), (5,6), (10,13)]
idx_region_map[3] = [(15,17), (19,20)]
# Which can be represented as follows:
#
# |012345678901234567890|
# 0|ooo----oooo----------|
# 1|----oo------------oo-|
# 2|---o-oo---oooo-------|
# 3|---------------ooo-oo|
# ...
def filter_overlaps(string_length, idx_region_map):
region_idx_map = {}
occupied = [False for i in range(string_length)]
for idx, regions in idx_region_map.items():
for region in regions:
start, end = region[0], region[1] + 1
overlaps = any(occupied[start:end])
if not overlaps:
for i in range(start, end):
occupied[i] = True
region_idx_map[region] = idx
return region_idx_map
# Prints: {(3, 3): 2, (4, 5): 1, (18, 19): 1, (7, 10): 0, (0, 2): 0, (15, 17): 3}
print filter_overlaps(string_length, idx_region_map)
这似乎足以满足我的需求,但我很想知道有哪些替代算法可以解决这个问题。例如,使用不同的数据结构或比上述更有效的东西。