python数字合并提高_将重叠的数字范围合并为连续范围

那么,记录每个位置的起点和终点以及每个位置所属范围的数量如何?在def overlap_alignments(align, overlap):

# create a list of starts and ends

stends = [ (a[0], 1) for a in align ]

stends += [ (a[1] + overlap, -1) for a in align ]

stends.sort(key=lambda x: x[0])

# now we should have a list of starts and ends ordered by position,

# e.g. if the ranges are 5..10, 8..15, and 12..13, we have

# (5,1), (8,1), (10,-1), (12,1), (13,-1), (15,-1)

# next, we form a cumulative sum of this

s = 0

cs = []

for se in stends:

s += se[1]

cs.append((se[0], s))

# this is, with the numbers above, (5,1), (8,2), (10,1), (12,2), (13,1), (15,0)

# so, 5..8 belongs to one range, 8..10 belongs to two overlapping range,

# 10..12 belongs to one range, etc

# now we'll find all contiguous ranges

# when we traverse through the list of depths (number of overlapping ranges), a new

# range starts when the earlier number of overlapping ranges has been 0

# a range ends when the new number of overlapping ranges is zero

prevdepth = 0

start = 0

combined = []

for pos, depth in cs:

if prevdepth == 0:

start = pos

elif depth == 0

combined.append((start, pos-overlap))

prevdepth = depth

return combined

这将更容易画出来,而不是解释。(是的,累积的总和可以用更短的空间来写,但我发现这样更清晰。)

为了以图形方式解释这一点,让我们输入([5,10],[8,15],[12,13],[16,20]),重叠=1。在

^{pr2}$

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值